var DEFAULT_SERVER = 'beorganized.org';

var LATEST_NEWS = '<b>New!</b> Recurred tasks, iCal support and other new features, <a href="http://dev.beorganized.org/2008/10/09/a-lot-of-new-features/" class="tag_link" target="_blank">click here for details</a>';

// var SITE_HEADER = '<div class="header_logo">Be Organized!</div><div class="latest_news">'+LATEST_NEWS+'</div><div class="project_link"><img src="im/types/p5.png" class="png_img"/><a href="http://dev.beorganized.org/" target="_blank" class="link_text tag_link">Project page</a><br/><img src="im/action/help.png" class="png_img"/><a href="http://dev.beorganized.org/tour/" target="_blank" class="link_text tag_link">Help</a></div>';
// 
var SITE_HEADER = '<div class="header_logo"><img src="logo03.png" border="0"/></div><div class="latest_news">'+LATEST_NEWS+'</div><div class="project_link"><img src="im/types/p5.png" class="png_img"/><a href="http://dev.beorganized.org/" target="_blank" class="link_text tag_link">Project page</a><br/><img src="im/action/help.png" class="png_img"/><a href="http://dev.beorganized.org/tour/" target="_blank" class="link_text tag_link">Help</a></div>';

var TYPE_TEXT = 0;
var TYPE_IMAGE = 1;
var TYPE_AUDIO = 2;
var TYPE_TASK = 3;
var TYPE_EVENT = 4;
var TYPE_BMARK = 5;
var TYPE_FILE = 6;

var APIURL = null;
var SERVERURL = null;
var token = null;
var user = null;

var statusString = '';

var titleSuffix = " :: BeOrganized!";

var printTitle = '';

var getReadableFileSize = function(size){
	if(size<1024)
		return size+' B';
	if(size>1024*1024)
		return Math.round(size/(1024*1024))+' MB';
	return Math.round(size/(1024))+' KB';
}

var setTitle = function(s){
	document.title = s+titleSuffix;
	printTitle = s;
}

var getWindowHeight = function(aGoodSize, aPadding){
	var goodSize = aGoodSize?aGoodSize:500;
	var padding = aPadding?aPadding:150;
	if(mainPanel.getSize().height>goodSize+padding)
		return goodSize;
	return mainPanel.getSize().height-padding;
}

var generateRandomString = function(num){
	var chars = 'qwertyuiopasdfghjklzxcvbnm';
	var rstr = '';
	for (var i=0; i < num; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		rstr += chars.substring(rnum, rnum+1);
	}
	return rstr;
}

var showError = function(msg){
	Ext.MessageBox.show({
		title: 'Error:',
		msg: msg,
		width: 300,
		icon: Ext.MessageBox.ERROR,
		buttons: Ext.MessageBox.OK
	});		
}

var showInfo = function(msg){
	Ext.MessageBox.show({
		title: 'Information:',
		msg: msg,
		width: 300,
		icon: Ext.MessageBox.INFO,
		buttons: Ext.MessageBox.OK
	});		
}

var startNetwork = function(){
	if(++networkFlag>0){
		//Show panel
		Ext.get('network').show();
		if(statusBar)
			statusBar.showBusy('Requesting network...');
	}
}

var endNetwork = function(){
	if(--networkFlag==0){
		//Hide panel
		Ext.get('network').hide();
		if(statusBar)
			statusBar.clearStatus({
				useDefaults: true
			});
	}	
}

var networkFlag = 0;
var callAPI = function(apiName, params, okCallback, errorCallback){
	var reader = new Ext.data.ScriptTagProxy({
		url: APIURL+"/api/"+apiName
	});
	reader.on('loadexception', function(o, obj, arg){
		endNetwork();
		showError('Connection to server failed. Server doesn\'t responding');
		if(errorCallback)
			errorCallback();
	});
	params.json = true;
	if(token)
		params.token = token;
	if(params.object){
		params.object = Ext.encode(params.object);
	}
	startNetwork();
	reader.load(params, null, function(object, arg, success){
		if(success){
			endNetwork();
			if(object.error){
				
				//Error decoding:
				
				var err = "Unknown error";
				
				if('DB_ERROR'==object.error)
					err = 'Database error, please try again';
				if('INVALID_END_DATE'==object.error)
					err = 'Invalid event end date provided. Please check entered data';
				if('INVALID_IMAGE'==object.error)
					err = 'Cannot upload file. Maybe file is too big';
				if('INVALID_LOGIN'==object.error)
					err = 'Invalid login name: Only alphanumeric and "_" characters allowed';
				if('INVALID_NAME'==object.error)
					err = 'Invalid name provided. This field is required';
				if('INVALID_START_DATE'==object.error)
					err = 'Invalid event start date. Please check entered data';
				if('INVALID_URL'==object.error)
					err = 'Invalid URL provided';
				if('INVALID_USER'==object.error)
					err = 'Invalid user name provided';
				if('INVALID_USER_PASS'==object.error)
					err = 'Invalid user name or password';
				if('LOGIN_TOO_SHORT'==object.error)
					err = 'Login name is too short, minimum length - 5 characters';
				if('NAME_TOO_SHORT'==object.error)
					err = 'Name is too short, minimum length - 5 characters';
				if('NO_PERMISSION'==object.error)
					err = 'You have no permission for this operation. Please check that someone granted you sufficient permissions';
				if('PASSWORD_TOO_SHORT'==object.error)
					err = 'Password too short, minimum length - 5 characters';
				if('START_DATE_LESS_END_DATE'==object.error)
					err = 'Event finish date is earlier than start date. Please provide correct dates';
				if('UPLOAD_FAILED'==object.error)
					err = 'File upload failed. Please upload another file';
				if('URL_TOO_LONG'==object.error)
					err = 'URL is too long. Maximum length is 255 characters';
				if('USER_EXISTS'==object.error)
					err = 'User with this name already exists. Please provide another one';
				// if(''==object.error)
				// 	err = '';
				
				showError(err);
				if(errorCallback)
					errorCallback();
				return;
			}
			okCallback(object);
		}
	});
	
}

var note = null;

var escapeHTML = function(s){
	if(!s)
		return '';
	var res = s.replace(/</g, '&lt;');
	res = res.replace(/>/g, '&gt;');
	res = res.replace(/\n/g, '<br/>');
	return res;
};

var logoutButton = null;

var profileButton = null;

var mainTree = null;

var refreshButton = null;

var leftToolbar = null;

var starButton = null;

var starButton = null;

var reloadNoteButton = null;

var archiveButton = null;

var permissionsButton = null;
var agendaButton = null;

var moveUpButton = null;

var moveDownButton = null;

var sortByManualButton = null;
var sortByNameButton = null;
var sortByCreateDateButton = null;
var sortByEditDateButton = null;
var sortByAsc = null;
var sortByDesc = null;

var quickTaskToggle = null;
var quickTaskField = null;
var quickTaskHelp = null;

var newItemText = null;
var newTextButton = null;

var newImageButton = null;
var newFileButton = null;

//var newAudioButton = null;

var newTaskButton = null;

var newEventButton = null;

var newBMarkButton = null;

var loadSubItemButton = null;

var printButton = null;

var moreButton = null;

var starToolbar = null;

var mainToolbar = null;

var contentPanel = null;

var rightPanel = null;
//, renderer: userRenderer

var tagStore = null;

var tagGrid = null;

var tagPanel = null;

var headerPanel = null;

var sortMenu = null;
// 
var exportMenu = null;	

var clearMenu = null;	

var convertMenu = null;	

var toTextMenu = null;
var toTaskMenu = null;
var toEventMenu = null;
var toBookmarkMenu = null;

var toImageMenu = null;
var toFileMenu = null;
// 
var mainPanel = null;

var sortToolbar = null;

var newToolbar = null;
	
var tagsToolbar = null;

var focusRequestor = null;

var statusBar = null;
var statusBarTime = null;
var statusBarCalendarButton = null;
var statusBarCalendar = null;

var dateFormat = 'd/m/y';

var timeFormat = 'g:i A';

var icalItem = null;
var icalTasksItem = null;

var createNoteText = function(note, level){
	var html = '<div class="node_header'+level+'"><img src="im/types/p'+note.icon+'.png" class="png_img"/><span class="link_text">'+escapeHTML(note.text)+'</span></div>';
	
	//Note content:
	switch(parseInt(note.type)){
		case TYPE_TEXT:
			html += '<code class="code">'+escapeHTML(note.textContent)+'</code>';
			break;
		case TYPE_IMAGE:
			if(parseInt(note.fileSize)>0)
				html += '<div>File name: '+note.fileName+', size: '+getReadableFileSize(parseInt(note.fileSize))+'</div><table width="100%" border="0"><tr><td align="center"><a href="'+APIURL+'/api/file.Download?sharecode='+note.shareCode+'" target="_blank"><img src="'+APIURL+'/api/file.Download?sharecode='+note.shareCode+'&width='+Math.floor(contentPanel.getSize().width/1.25)+'" class="img_show"/></a></td></tr></table>';
			break;
		case TYPE_AUDIO:
			break;
		case TYPE_TASK:
			html += '<div><img src="im/priority/p'+note.priority+'.png" class="png_img"/>';
			if(note.completed=='true'){
				html += '<img src="im/action/complete.png" class="png_img"/> Completed</div>';
			}else
				html += 'Incomplete</div>';
			if(note.datesInfo){
				html += '<div><span class="urgent'+note.urgentLevel+'">Due date: '+note.datesInfo+'</span>';
				if(note.recurred=='true')
					html += ', '+note.recurrenceInfo;
				html += '</div>'
			}
			html += '<div class="code"><code class="code">'+escapeHTML(note.textContent)+'</code></div>';
			break;
		case TYPE_EVENT:
			if(note.datesInfo){
				html += '<div><span class="urgent'+note.urgentLevel+'">'+note.datesInfo+'</span>';
				if(note.recurred=='true')
					html += ', '+note.recurrenceInfo;
				html += '</div>'
			}
			html += '<div class="code"><code class="code">'+escapeHTML(note.textContent)+'</code></div>';
			break;
		case TYPE_BMARK:
			html += '<a href="'+note.url+'" target="_blank">'+note.url+'</a>';
			html += '<div class="code"><code class="code">'+escapeHTML(note.textContent)+'</code></div>';
			break;
		case TYPE_FILE:
			if(parseInt(note.fileSize)>0)
				html += '<div>File name: '+note.fileName+', size: '+getReadableFileSize(parseInt(note.fileSize))+'</div><a href="'+APIURL+'/api/file.Download?sharecode='+note.shareCode+'" target="_blank">Download file</a>';
			break;
	}
	return html;
}

var LOADING_TEXT = '<div class="node_header0"><img src="js/resources/images/default/grid/loading.gif" border="0"/><span class="link_text">Loading...</span></div>';

var clearContentPanel = function(showBusy, noteIcon, noteText){
	var div = document.getElementById('printme');
	if(showBusy){
		if(noteText && noteIcon){
			var html = '<div class="node_header0"><img src="im/types/p'+noteIcon+'.png" class="png_img"/><span class="link_text">'+escapeHTML(noteText)+'</span></div>'+LOADING_TEXT;
			div.innerHTML = html;
		}else{
			div.innerHTML = LOADING_TEXT;
		}
		return;
	}
	if(div)
		div.innerHTML = '';
	contentPanel.items.clear();
	
}

var expandNextNode = function(aPath, aIndex, aNode){
	aNode.select();
	aNode.expand();
	if(aIndex>=aPath.length)
		return;
	var lChild = aNode.findChild('id', aPath[aIndex]);
	if(lChild)
		expandNextNode(aPath, aIndex+1, lChild);
}

var expandNoteInTree = function(aPath){
	var lPath = aPath.split('/');
	expandNextNode(lPath, 2, mainTree.root);
}

var lastSelectedNoteID = null;

var selectNote = function(id){
	var node = mainTree.getNodeById(id);
	clearContentPanel(true, node.noteIcon, node.noteText);
	if(node){
		setTitle('Loading...');
		try{
			expandNoteInTree(node.getPath());			
		}catch(e){
			
		}
		lastSelectedNoteID = id;
		callAPI('GetNote', {
			noteid: id
		}, function(object){
			if(object.note.id!=lastSelectedNoteID)
				return;
			note = object.note;
			icalItem.setText('<a href="webcal://'+SERVERURL+'/api/xml.ICalExport?sharecode='+note.shareCode+'" class="tag_link">Events</a>');
			icalTasksItem.setText('<a href="webcal://'+SERVERURL+'/api/xml.ICalExport?sharecode='+note.shareCode+'&tasks=true" class="tag_link">Events and tasks</a>');
			
			note.canEdit = note.canEdit=='true';
			note.canCreate = note.canCreate=='true';
			note.canDelete = note.canDelete=='true';
			setTitle(note.text);
			starButton.toggle(note.starred=='true');
			//Enable/Disable buttons
			editButton.setVisible(note.canEdit);
			archiveButton.setVisible(note.canDelete && note.level!=0);
			permissionsButton.setVisible(note.user==user.login);
			clearMenu.setVisible(note.canDelete);
			moveUpButton.setVisible(note.canEdit && note.level!=0 && node.parentNode.id!='root');
			moveDownButton.setVisible(note.canEdit && note.level!=0 && node.parentNode.id!='root');
			loadSubItemButton.toggle(false);
			sortMenu.setVisible(note.canEdit);
			newToolbar.setVisible(note.canCreate);
			
			sortByManualButton.setChecked(note.sort==0, true);
			sortByNameButton.setChecked(note.sort==1, true);
			sortByCreateDateButton.setChecked(note.sort==2, true);
			sortByEditDateButton.setChecked(note.sort==3, true);
			
			sortByAsc.setChecked(note.sortType==0, true);
			sortByDesc.setChecked(note.sortType==1, true);
			
			convertMenu.setVisible(note.canEdit);
			
			var noteType = parseInt(note.type);
			toTextMenu.setVisible(noteType==TYPE_TASK || noteType==TYPE_EVENT || noteType==TYPE_BMARK);
			toTaskMenu.setVisible(noteType==TYPE_TEXT || noteType==TYPE_EVENT || noteType==TYPE_BMARK);
			toEventMenu.setVisible(noteType==TYPE_TASK || noteType==TYPE_TEXT || noteType==TYPE_BMARK);
			toBookmarkMenu.setVisible(noteType==TYPE_TASK || noteType==TYPE_EVENT || noteType==TYPE_TEXT);
			toImageMenu.setVisible(noteType==TYPE_FILE);
			toFileMenu.setVisible(noteType==TYPE_IMAGE);
//			tagsToolbar.items.add('Tags:');
			if(note.children[0].children){
				tagsToolbar.setVisible(true);
				for(var i = 0; i<tagsToolbar.items.getCount(); i++){
					tagsToolbar.items.get(i).destroy();
				}
				tagsToolbar.add({
					xtype: 'tbtext',
					text: 'Tags:'
				});
//				tagsToolbar.items.clear();
				for(var i=0; i<note.children[0].children.length; i++){
					var t = note.children[0].children[i];
					var b = new Ext.Toolbar.Button({
						text: escapeHTML(t.name),
						iconCls: 'tag',
						handler: function(){
							showTag(this.noteTag, this.getEl());
						}
					});
					b.noteTag = t.name;
					tagsToolbar.add(b);
				}
			}else{
				tagsToolbar.setVisible(false);
			}
			tagStore.removeAll();
			if(note.children[1].children){
				for(var i=0; i<note.children[1].children.length; i++){
					var t = note.children[1].children[i];
					tagStore.add(new Ext.data.Record({
						name: escapeHTML(t.name),
						count: parseInt(t.count)
					}));
				}
			}
			if(tagStore.getCount()>0){
				tagPanel.expand(false);
			}else{
				tagPanel.collapse(false);
			}
			//Refresh end
			var html = createNoteText(note, 0);
			clearContentPanel();
			contentPanel.add(new Ext.Panel({
				border: false,
				autoScroll: true,
				html: '<div class="viewnote" id="printme">'+html+'</div>'
			}));
			rightPanel.syncSize();
			mainPanel.doLayout();
			if(focusRequestor){
				focusRequestor.focus(true, 10);
				focusRequestor = null;
			}
		});
	}
}


var makeNode = function(parentNode, object, replaceWith){
	var text = escapeHTML(object.text);
	if(object.add_icon)
		text = '<img src="im/'+object.add_icon+'" class="png_img" width="10" height="10"/>&nbsp;'+text;
	var node = new Ext.tree.TreeNode({
		text: text,
		id: object.id,
		nodeType: 'node',
		allowDrag: parentNode.id!='root',
		icon: 'im/types/p'+object.icon+'.png',
		iconCls: 'png_img',
		parentID: parentNode.id
	});
	node.noteText = text;
	node.noteIcon = object.type;
	if(replaceWith){
		replaceWith.id = 'replacing';
		parentNode.insertBefore(node, replaceWith);
		replaceWith.remove();
	}
	else
		parentNode.appendChild(node);
	if(object.children){
		for(var i = 0; i<object.children.length; i++){
			var item = object.children[i];
			makeNode(node, item);
		}			
	}
	return node;
//	node.id = object.id;
}

var refreshNote = function(noteid, selectid){
	setTitle('Loading...');
	callAPI('LoadTree', {
		noteid: noteid
	}, function(object){
		var node = mainTree.getNodeById(noteid);
		if(node){
			makeNode(node.parentNode, object.note, node).expand();
			
			selectNote(selectid);
		}
	});		
}

var refreshMainTree = function(note){
	var noteID = 0;
	while(mainTree.root.childNodes.length>0){
		mainTree.root.childNodes[0].remove();
	}
	for(var i = 0; i<note.children.length; i++){
		if(i==0)
			noteID = note.children[i].id;
		makeNode(mainTree.root, note.children[i]);
	}
	selectNote(noteID);
};

var changeSort = function(object, sort, sortType){
	note.sort = sort;
	note.sortType = sortType;
	callAPI('ChangeSort', {
		noteid: note.id,
		sort: note.sort,
		sorttype: note.sortType
	}, function(object){
		refreshNote(object.note.id, object.note.id);
	});
};


var newNote = function(type, el){
	if(!note)
		return;
	var n = {
		id: note.id,
		type: type,
		text: note.text,
		customIcon: type
	};
	editNote(n, true, refreshNote, null, el);
}


// var Button = new Ext.Toolbar.Button({
// 	text: '',
// 	iconCls: '',
// 	handler: function(){
// 		
// 	}
// });
// 

//, sortByManualButton, sortByNameButton, sortByCreateDateButton, sortByEditDateButton

var stars = [];

var refreshStars = function(){
	callAPI('StarList',{},function(object){
		for(var i = 0; i < stars.length; i++){
			stars[i].button.destroy();
		}
		stars = object.list?object.list.children:[];
		for(var i = 0; i < stars.length; i++){
			var id = stars[i].id;
			var btn = new Ext.Toolbar.Button({
				text: escapeHTML(stars[i].text),
				iconCls: 'p'+stars[i].icon,
				handler: function(){
					selectNote(this.noteid);
				}
			});
			btn.noteid = id;
			stars[i].button = btn;
			starToolbar.add(btn);
		}
		starToolbar.setVisible(stars.length>0);
		rightPanel.syncSize();
		mainPanel.doLayout();
	});
};

var tagRenderer = function(value, meta, record){
	return '<a href="javascript:;" onclick="showTag(\''+String.escape(value)+'\'); return false;" class="tag_link"><img src="im/tags/tags.png" class="png_img"/><span class="link_text">'+value+'</span></a>';
};

var recalcFormats = function(){
	if(user.dateFormat=='dd.MM.yy')
		dateFormat = 'd.m.y';
	if(user.dateFormat=='yy-MM-dd')
		dateFormat = 'y-m-d';
	if(user.dateFormat=='MM/dd/yy')
		dateFormat = 'm/d/y';
	if(user.timeFormat=='H:mm')
		timeFormat = 'G:i';
}

var mainForm = function(){
	document.getElementById('logo_table').style.display = 'none';
	document.getElementById('loading').style.display = 'none';
	document.getElementById('footer').style.display = 'none';
	recalcFormats();
	setTitle('Loading...');
	logoutButton = new Ext.Toolbar.Button({
		text: 'Logout',
		tooltip: 'Terminates current session and shows login dialog',
		iconCls: 'logout',
		handler: function(){
			Ext.Msg.show({
				title:'Close session?',
				msg: 'Are you sure you want to close session?',
				buttons: Ext.Msg.YESNO,
				fn: function(buttonId){
						if(buttonId=='yes'){
							window.location.reload();
						}
					},
				icon: Ext.MessageBox.QUESTION
			});
		}
	});
	
	profileButton = new Ext.Toolbar.Button({
		text: 'Profile',
		iconCls: 'profile',
		tooltip: 'Modify your personal settings and change password',
		handler: function(){
			callAPI('user.GetCurrentUser', {}, function(object){
				user = object.user;
				editProfile(note.id, selectNote);
			})
		}
	});

	mainTree = new Ext.tree.TreePanel({
		region: 'center',
		rootVisible: false,
		animate: false,
		enableDD: true,
		border: false,
		ddAppendOnly: true,
		autoScroll: true,
		style: 'padding-top: 2px;',
		root: {
			nodeType: 'node',
			id: 'root',
			text: 'Loading...',
			leaf: false
		}
	});

	mainTree.on('enddrag', function(object, node, event){
		if(node.attributes.parentID==node.parentNode.id){
			return;
		}
		clearContentPanel(true, node.noteIcon, node.noteText);
		callAPI('MoveNote', {
			noteid: node.id,
			parentid: node.parentNode.id
		}, function(object){
//			refreshNote(node.attributes.parentID, node.id)
			refreshNote(node.parentNode.id, node.id);
		}, function(){
			refreshNote(node.parentNode.id, node.id);
			refreshNote(node.attributes.parentID, node.id)
		});
		//Calling MoveNode
	});

	mainTree.on('click', function(node){
		selectNote(node.id);
	});
	
	refreshButton = new Ext.Toolbar.Button({
		text: 'Refresh',
		tooltip: 'Reload your notes',
		iconCls: 'refresh',
		handler: function(){
			callAPI('LoadTree', {}, function(object){
				refreshMainTree(object.note);
			});
		}
	});

	leftToolbar = new Ext.Toolbar({
		region: 'north',
		items: [
			refreshButton, logoutButton, profileButton
		]
	});

	reloadNoteButton  = new Ext.Toolbar.Button({
		text: 'Reload',
		tooltip: 'Reload current note',
		iconCls: 'reload_note',
		handler: function(){
			if(note)
				refreshNote(note.id, note.id);
		}
	});
	
	starButton = new Ext.Toolbar.Button({
		text: 'Star it!',
		tooltip: 'Add current note to favorites toolbar (Always appears on top of window)',
		iconCls: 'star',
		enableToggle: true,
		handler: function(){
			callAPI('StarNote', {
				noteid: note.id
			}, function(object){
				refreshStars();
				starButton.toggle(object.result.added=='true');
			});
		}
	});

	editButton = new Ext.Toolbar.Button({
		text: 'Edit',
		tooltip: 'Edit current note',
		iconCls: 'edit',
		handler: function(){
			editNote(note, false, refreshNote, refreshStars, this.getEl());
		}
	});

	printButton = new Ext.Toolbar.Button({
		text: 'Print',
		tooltip: 'Print contents of current note',
		iconCls: 'print',
		handler: function(){
			window.open('print.html');
		}
	});

	moreButton = new Ext.Toolbar.Button({
		text: 'More...',
		tooltip: 'Displays toolbar with additional actions',
		iconCls: 'more',
		enableToggle: true,
		handler: function(){
			sortToolbar.setVisible(moreButton.pressed);
			rightPanel.syncSize();
			mainPanel.doLayout();
		}
	});

	loadSubItemButton = new Ext.Toolbar.Button({
		text: 'Subnotes',
		tooltip: 'Loads contents of all subnotes. Good for reviewing and printing',
		iconCls: 'subnotes',
		enableToggle: true,
		
		handler: function(){
			if(note){
				clearContentPanel(true, note.type, escapeHTML(note.text));
				
			}else{
				clearContentPanel(true);
			}
			
			var generateNoteText = function(note, level){
				var result = createNoteText(note, level);
				if(note.children){
					for(var i = 0; i<note.children.length; i++){
						var item = note.children[i];
						result += generateNoteText(item, level>1?level:level+1);
					}			
				}
				return level==0?result:'<div class="viewnote">'+result+'</div>';
			}
			if(loadSubItemButton.pressed){
				//Load subtree
				callAPI('LoadTree', {
						noteid: note.id,
						loaddata: 'true'
					}, function(object){
					var text = '<div id="printme" class="viewnote">'+generateNoteText(object.note, 0)+'</div>';
					clearContentPanel();
					contentPanel.add(new Ext.Panel({
						border: false,
						autoScroll: true,
						html: text
					}));				
					contentPanel.doLayout();				
				});
			}else{
				clearContentPanel();
				contentPanel.add(new Ext.Panel({
					border: false,
					autoScroll: true,
					html: '<div class="viewnote" id="printme">'+createNoteText(note, 0)+'</div>'
				}));				
				contentPanel.doLayout();				
			}

		}
	});

	archiveButton = new Ext.Toolbar.Button({
		text: 'Archive',
		tooltip: 'Removes current note and all it\'s subnotes',
		iconCls: 'archive',
		handler: function(){
			Ext.Msg.show({
				title:'Archive note?',
				msg: 'Are you sure you want to archive note "'+escapeHTML(note.text)+' and all it\' children?"?',
				buttons: Ext.Msg.YESNO,
				fn: function(buttonId){
						if(buttonId=='yes'){
							callAPI('RemoveNote', {
								noteid: note.id
							}, function(object){
								refreshNote(object.note.parentid, object.note.parentid);
								refreshStars();
							});
						}
					},
				icon: Ext.MessageBox.QUESTION
			});
		}
	});

	agendaButton = new Ext.Toolbar.Button({
		text: 'Agenda',
		tooltip: 'Shows list of scheduled events and tasks',
		iconCls: 'agenda',
		handler: function(){
			if(note)
				showAgenda(this.getEl());
		}
	});

	moveUpButton = new Ext.Toolbar.Button({
		text: 'Up',
		tooltip: 'Moves note up. Works only with manual order active',
		iconCls: 'move_up',
		handler: function(){
			if(!note)
				return;
			clearContentPanel(true, note.type, note.text);
			callAPI('MoveUp', {
				noteid: note.id
			}, function(object){
				refreshNote(object.note.parentid, object.note.id);
			});
		}
	});

	moveDownButton = new Ext.Toolbar.Button({
		text: 'Down',
		tooltip: 'Moves note down. Works only with manual order active',
		iconCls: 'move_down',
		handler: function(){
			if(!note)
				return;
			clearContentPanel(true, note.type, note.text);
			callAPI('MoveDown', {
				noteid: note.id
			}, function(object){
				refreshNote(object.note.parentid, object.note.id);
			});
		}
	});
	
	permissionsButton = new Ext.Toolbar.Button({
		text: 'Permissions',
		tooltip: 'Share current note and all it\'s children with other users',
		iconCls: 'permissions',
		handler: function(){
			if(note)
				editPermissions(note.id, this.getEl());
		}
	});

	sortByManualButton = new Ext.menu.CheckItem({
		text: 'Manual order',
	//	iconCls: 'sort_by',
		group: 'sort',
	//	enableToggle: true,
		checkHandler: function(item, checked){
			if(checked)
				changeSort(this, 0, note.sortType);
		}
	});
	
	sortByNameButton = new Ext.menu.CheckItem({
		text: 'By name',
	//	iconCls: 'sort_by',
		group: 'sort',
	//	enableToggle: true,
		checkHandler: function(item, checked){
			if(checked)
				changeSort(this, 1, note.sortType);
		}
	});
	
	sortByCreateDateButton = new Ext.menu.CheckItem({
		text: 'By date created',
	//	iconCls: 'sort_by',
		group: 'sort',
	//	enableToggle: true,
		checkHandler: function(item, checked){
			if(checked)
				changeSort(this, 2, note.sortType);
		}
	});
	
	sortByEditDateButton = new Ext.menu.CheckItem({
		text: 'By date edited',
	//	iconCls: 'sort_by',
		group: 'sort',
	//	enableToggle: true,
		checkHandler: function(item, checked){
			if(checked)
				changeSort(this, 3, note.sortType);
		}
	});
	
	sortByAsc = new Ext.menu.CheckItem({
		text: 'Ascending',
		group: 'sortType',
		checkHandler: function(item, checked){
			if(checked)
				changeSort(this, note.sort, 0);
		}
	});
	
	sortByDesc = new Ext.menu.CheckItem({
		text: 'Descending',
		group: 'sortType',
		enableToggle: true,
		checkHandler: function(item, checked){
			if(checked)
				changeSort(this, note.sort, 1);
		}
	});
	
	quickTaskToggle = new Ext.Toolbar.Button({
		text: 'Quick task...',
		tooltip: 'Quickly add tasks to current note by typing task name and pressing Enter',
	 	iconCls: 'quick_add',
		enableToggle: true,
	 	handler: function(){
			newItemText.setVisible(!quickTaskToggle.pressed);
			newTextButton.setVisible(!quickTaskToggle.pressed);
			newImageButton.setVisible(!quickTaskToggle.pressed);
			newFileButton.setVisible(!quickTaskToggle.pressed);
			newTaskButton.setVisible(!quickTaskToggle.pressed);
			newEventButton.setVisible(!quickTaskToggle.pressed);
			newBMarkButton.setVisible(!quickTaskToggle.pressed);
			quickTaskField.setVisible(quickTaskToggle.pressed)
			quickTaskHelp.setVisible(quickTaskToggle.pressed)
			if(quickTaskToggle.pressed){
				quickTaskField.setValue('');
				quickTaskField.focus(false, 10);
			}else{
				
			}
	 	}
	});
	
	quickTaskField = new Ext.form.TextField({
		width: '300px',
		enableKeyEvents: true
	});
	
	// quickTaskHelp = new Ext.Toolbar.TextItem('&nbsp;<a href="http://dev.beorganized.org/features/quick-syntax/" target="_blank" class="tag_link">Need help? Click to know more</a>');
	quickTaskHelp = new Ext.Toolbar.Button({
		iconCls: 'help_quick',
		tooltip: 'Need help? Click to know more',
		handler: function(){
			window.open('http://dev.beorganized.org/features/quick-syntax/');
		}
	});
	
	quickTaskField.on('keydown', function(item, event){
		if(event.getKey()==Ext.EventObject.ENTER && item.getValue() && note){
			callAPI('SaveNote', {
				id: note.id,
				type: TYPE_TASK,
				name: item.getValue(),
				forceutf: 'true',
				quickadd: 'true',
				newNote: 'true',
				rnd: generateRandomString(15)
			}, function(object){
				focusRequestor = quickTaskField;
				refreshNote(note.id, note.id);
				quickTaskField.setValue('');
				quickTaskField.focus(false, 10);
			})
		}
	});
	
	newItemText = new Ext.Toolbar.TextItem({
		text: 'New:'
	});

	newTextButton = new Ext.Toolbar.Button({
		text: 'Text note',
		tooltip: 'Add new text note',
	 	iconCls: 'p0',
	 	handler: function(){
	 		newNote(0, this.getEl());
	 	}
	});

	newImageButton = new Ext.Toolbar.Button({
		text: 'Image',
		tooltip: 'Upload new image',
	 	iconCls: 'p1',
	 	handler: function(){
	 		newNote(1, this.getEl());
	 	}
	});

	newFileButton = new Ext.Toolbar.Button({
		text: 'File',
		tooltip: 'Upload new file',
	 	iconCls: 'p6',
	 	handler: function(){
	 		newNote(TYPE_FILE, this.getEl());
	 	}
	});

	//var newAudioButton = new Ext.Toolbar.Button({
	//	text: 'Audio note',
	// 	iconCls: 'p2',
	// 	handler: function(){
	// 		newNote(2);
	// 	}
	//});
	//
	newTaskButton = new Ext.Toolbar.Button({
		text: 'Task',
		tooltip: 'Add new task',
	 	iconCls: 'p3',
	 	handler: function(){
	 		newNote(3, this.getEl());
	 	}
	});

	newEventButton = new Ext.Toolbar.Button({
		text: 'Event',
		tooltip: 'Add new event',
	 	iconCls: 'p4',
	 	handler: function(){
	 		newNote(4, this.getEl());
	 	}
	});

	newBMarkButton = new Ext.Toolbar.Button({
		text: 'Bookmark',
		tooltip: 'Add new bookmark',
	 	iconCls: 'p5',
	 	handler: function(){
	 		newNote(5, this.getEl());
	 	}
	});
	
	starToolbar = new Ext.Toolbar({
		region: 'north',
		items: [
			'<img src="im/action/star.png"/>'
		]
	});

	starToolbar.setVisible(false);
	
	mainToolbar = new Ext.Toolbar({
		region: 'north',
		items: [agendaButton, '-', starButton, reloadNoteButton, editButton, archiveButton, '-', loadSubItemButton, printButton, '-', moreButton
		]
	});

	contentPanel = new Ext.Panel({
		layout: 'fit',
		border: false,
		items: {
			border: false,
			autoScroll: true,
			html: '<div class="viewnote" id="printme">'+LOADING_TEXT+'</div>'
		}
	});

	rightPanel = new Ext.Panel({
		tbar: mainToolbar,
		layout: 'fit',
		region: 'center',
		items: contentPanel
	});
	//, renderer: userRenderer

	tagStore = new Ext.data.SimpleStore({
		fields: [
			{name: 'name'},
			{name: 'count'}
		]
	});

	tagGrid = new Ext.grid.GridPanel({
		store: tagStore,
		columns: [
			{id: 'first', header: 'Tag', dataIndex: 'name', sortable: true, renderer: tagRenderer},
			{header: 'Notes', dataIndex: 'count', width: 48, sortable: true, align: 'right'}
		],
		autoExpandColumn: 'first',
		viewConfig: {
            forceFit:true
        },
		border: false
	});

	tagPanel = new Ext.Panel({
		region: 'east',
		collapsible: true,
		title: 'Tags',
		split: true,
		hideCollapseTool: true,
		width: 200,
		layout: 'fit',
		collapsed: true,
		items: tagGrid
	});

	sortMenu = new Ext.Toolbar.Button({
		text: 'Sorting',
		iconCls: 'sort_by',
		tooltip: 'Change sorting method and direction of subnotes',
		menu: {
			items:[
				'<b class="menu-title">Sorting type:</b>',
				sortByManualButton, sortByNameButton, sortByCreateDateButton, sortByEditDateButton,
				'<b class="menu-title">Sorting direction:</b>',
				sortByAsc, sortByDesc
			]
		}
	});
	icalItem = new Ext.menu.Item({
		text: 'iCal calendar (events)',
		iconCls: 'export_ical',
		handler: function(){
			window.open('webcal://'+SERVERURL+'/api/xml.ICalExport?sharecode='+note.shareCode);
		}
	});
	
	icalTasksItem = new Ext.menu.Item({
		text: 'iCal calendar (events and tasks)',
		iconCls: 'export_ical',
		handler: function(){
			window.open('webcal://'+SERVERURL+'/api/xml.ICalExport?sharecode='+note.shareCode+'&tasks=true');
		}
	});
	
	exportMenu = new Ext.Toolbar.Button({
		text: 'Import/Export',
		iconCls: 'export',
		tooltip: 'Various import and export methods',
		menu: {
			items:[
				{
					text: 'Export as XML',
					iconCls: 'export_xml',
					handler: function(){
						window.open(APIURL+'/api/xml.XMLExport?token='+token+"&noteid="+note.id);
					}
				},
				{
					text: 'Import XML',
					iconCls: 'import_xml',
					handler: function(){
						startImport(this);
					}
				},
				'<b class="menu-title">Export as iCal calendar</b>',
				icalItem, icalTasksItem
			]
		}
	});	
	
	var convertTo = function(newType){
		if(!note)
			return;
		editNote(note, false, refreshNote, refreshStars, null, true, newType);
	}
	
	toTextMenu = new Ext.menu.Item({
		text: 'Text note',
		iconCls: 'p0',
		handler: function(){
			convertTo(0);
		}
	});
	
	toTaskMenu = new Ext.menu.Item({
		text: 'Task',
		iconCls: 'p3',
		handler: function(){
			convertTo(3);
		}
	});
	
	toEventMenu = new Ext.menu.Item({
		text: 'Event',
		iconCls: 'p4',
		handler: function(){
			convertTo(4);
		}
	});
	
	toBookmarkMenu = new Ext.menu.Item({
		text: 'Bookmark',
		iconCls: 'p5',
		handler: function(){
			convertTo(5);
		}
	});
	
	toImageMenu = new Ext.menu.Item({
		text: 'Image',
		iconCls: 'p1',
		handler: function(){
			convertTo(TYPE_IMAGE);
		}
	});
	
	toFileMenu = new Ext.menu.Item({
		text: 'File',
		iconCls: 'p6',
		handler: function(){
			convertTo(TYPE_FILE);
		}
	});
	
	convertMenu = new Ext.Toolbar.Button({
		text: 'Convert to',
		tooltip: 'Change type of current note',
		iconCls: 'convert',
		menu: {
			items:[
				toTextMenu, toTaskMenu, toEventMenu, toBookmarkMenu, toImageMenu, toFileMenu
				]
			}
	});
		
	clearMenu = new Ext.Toolbar.Button({
		text: 'Cleanup',
		tooltip: 'Various clean procedures',
		iconCls: 'clear',
		menu: {
			items:[
				{
					text: 'Clear completed tasks',
					iconCls: 'clear_tasks',
					handler: function(){
						if(!note)
							return;
						Ext.Msg.show({
							title:'Clear completed tasks?',
							msg: 'Are you sure you want to continue? All completed tasks and al it\'s children will be archived',
							buttons: Ext.Msg.YESNO,
							fn: function(buttonId){
									if(buttonId=='yes'){
										callAPI('agenda.ClearCompletedTasks', {
											noteid: note.id
										}, function(object){
											showInfo('Operation done. Tasks archived total: '+object.result.count);
											refreshNote(note.id, note.id);
										})
									}
								},
							icon: Ext.MessageBox.QUESTION
						});
					}
				},
				{
					text: 'Clear past events',
					iconCls: 'clear_events',
					handler: function(){
						if(!note)
							return;
						Ext.Msg.show({
							title:'Clear past events?',
							msg: 'Are you sure you want to continue? All past events and al it\'s children will be archived',
							buttons: Ext.Msg.YESNO,
							fn: function(buttonId){
									if(buttonId=='yes'){
										callAPI('agenda.ClearPastEvents', {
											noteid: note.id
										}, function(object){
											showInfo('Operation done. Events archived total: '+object.result.count);
											refreshNote(note.id, note.id);
										})
									}
								},
							icon: Ext.MessageBox.QUESTION
						});
					}
				}
			]
		}
	});	
	
	var dt = new Date();
	
	statusBarTime = new Ext.Toolbar.Button({
		text: dt.format(dateFormat+' '+timeFormat),
		iconCls: 'calendar_btn',
		menu: new Ext.menu.DateMenu({
			handler: function(){
				return false;
			}
		})
	});
	
	statusBar = new Ext.StatusBar({
		defaultText: statusString,
		region: 'south',
		items: [
			'-', statusBarTime
		]
	});
	setInterval(function(){
		var dt = new Date();
		statusBarTime.setText(dt.format(dateFormat+' '+timeFormat));
	}, 10000);
	
	headerPanel = new Ext.Panel({
			height: 47,
			region: 'north',
			baseCls: 'header_panel',
			tooltip: 'Build No: '+BUILD_NO,
			html: '<div id="site_header"></div>'
	});
	
	mainPanel = new Ext.Viewport({
		layout: 'border',
		items:[headerPanel,
		{
			region: 'center',
			layout: 'border',
			border: false,
			items: [
				{
//					collapsible: true,
					region: 'west',
					width: 250,
					title: 'Your notes:',
					split: 'true',
					layout: 'border',
					items: [
						leftToolbar, mainTree
					]
				}, rightPanel, tagPanel, starToolbar
			]
		}, statusBar]
	});
	
	// var map = new Ext.KeyMap(document, {
	//     key: 't', 
	//     fn: function(){
	// 		console.log('Show quick tag');
	// 	},
	//     scope: mainPanel
	// });
	// 
	sortToolbar = new Ext.Toolbar({
		renderTo: rightPanel.tbar,
		items: [
			moveUpButton, moveDownButton, sortMenu, exportMenu, clearMenu, convertMenu, permissionsButton
		]
	});
	
	sortToolbar.setVisible(false);
	
	newToolbar = new Ext.Toolbar({
		renderTo: rightPanel.tbar,
		items: [
			quickTaskToggle, '-', quickTaskField, quickTaskHelp, newItemText, newTextButton, newImageButton, newTaskButton, newEventButton, newBMarkButton, newFileButton
		]
	});

	quickTaskField.hide();
	quickTaskHelp.hide();
	
	tagsToolbar = new Ext.Toolbar({
		renderTo: rightPanel.tbar,
		items: []
	});

	tagsToolbar.setVisible(false);
	
	callAPI('LoadTree', {}, function(object){
		refreshMainTree(object.note);
	});
	
	rightPanel.syncSize();
	mainPanel.doLayout();
	refreshStars();
	document.getElementById('site_header').innerHTML = SITE_HEADER;
//	headerPanel.getEl().innerHTML = SITE_HEADER;
//	mainPanel.syncSize();

//	sortToolbar.renderTo(rightPanel.tbar);
};

var startImport = function(el){
	var uploadField = new Ext.form.FileUploadField({
			fieldLabel: 'Upload file',
			anchor: '99%',
			allowBlank: false,
			name: 'file'
	});
	
	var idField = new Ext.form.Hidden({
		name: 'id',
		value: note.id
	});
	
	var randomField = new Ext.form.Hidden({
		name: 'rnd',
		value: generateRandomString(20)
	});
	
	var tokenField = new Ext.form.Hidden({
		name: 'token',
		value: token
	});
	
	var jsonField = new Ext.form.Hidden({
		name: 'json',
		value: 'true'
	});
	
	var form = new Ext.form.FormPanel({
		frame: true,
		url: APIURL+'/api/xml.Import',
		fileUpload: true,
		labelAlign: 'right',
		autoHeight: true,
		items: [uploadField, idField, randomField, tokenField, jsonField],
		buttons:[
			{
				text: 'Import',
				handler: function(){
					if(form.getForm().isValid()){
						Ext.Msg.show({
							title:'Import XML?',
							msg: 'Warning! Current element and all it\'s children will be replaced with elements from this file. Are you sure you want to continue?',
							buttons: Ext.Msg.YESNO,
							fn: function(buttonId){
									if(buttonId=='yes'){
										randomField.setValue(generateRandomString(20));
										startNetwork();
										form.getForm().submit();
									}
								},
							icon: Ext.MessageBox.QUESTION
						});
					}
				}
			}
		]
	});
	
	var closeWin = function(id1, id2){
			win.close();
			refreshNote(id1, id2);
			if(refreshStars)
				refreshStars();			
	}

	form.getForm().on('actioncomplete', function(f, action){
		endNetwork();
		callAPI('xml.CheckSaveResult', {
			rnd: randomField.getValue()
		}, function(object){
			closeWin(note.id, note.id);
		})
	});
	
	var win = new Ext.Window({
		width: 600,
		autoHeight: true,
		title: 'Import XML',
		modal: true,
		layout: 'fit',
		items: form
	});
	win.on('close', function(){
		setTitle(note.text);
	})
	setTitle('Import XML');
	win.show();		
}

var tagWin = null;

var agendaWin = null;

var showTag = function(tag, el){
//	CallAPI('')
	var getList = function(){
		callAPI('GetTaggedNotes', {
			noteid: note.id,
			object: {
				tag: {
					tag: tag
				}
			}
		}, function(object){
			store.removeAll();
			if(object.list.children){
				for(var i = 0; i<object.list.children.length; i++){
					var n = object.list.children[i];
					store.add(new Ext.data.Record({
						id: n.id,
						text: escapeHTML(n.text),
						icon: n.icon,
						add_icon: n.add_icon
					}));
				}
			}
		});
	}
	var store = new Ext.data.SimpleStore({
		fields: [
			{name: 'id'},
			{name: 'text'},
			{name: 'icon'},
			{name: 'add_icon'}
		]
	});
	var elementRenderer = function(value, meta, record){
		var res = '<a class="tag_link" href="javascript:;" onclick="selectNote('+record.get('id')+'); tagWin.close(); return false;"><img src="im/types/p'+record.get('icon')+'.png" class="png_img"/>';
		if(record.get('add_icon')){
			res += '<img src="im/'+record.get('add_icon')+'" class="png_img"/>';
		}
		res += '<span class="link_text">'+value+'</span></a>';
		return res;
	}
	
	var grid = new Ext.grid.GridPanel({
		store: store,
		columns: [
			{id: 'first', header: 'Note', dataIndex: 'text', renderer: elementRenderer, sortable: true}
		],
		autoExpandColumn: 'first'
	});
	
	tagWin = new Ext.Window({
		width: 350,
		height: getWindowHeight(),
		title: 'Tagged by '+escapeHTML(tag)+':',
		modal: true,
		iconCls: 'tag',
		layout: 'fit',
		items: [
			grid
		]
	});
	tagWin.on('close', function(){
		setTitle(note.text);
	})
	setTitle('Tagged by '+tag);
	tagWin.show();
	getList();
}

var editPermissions = function(noteid, callee){
//	Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
	var refreshList = function(){
		store.removeAll();
		callAPI('permission.PermissionList', {
			noteid: noteid
		}, function(object){
			if(object.list.children){
				for(var i = 0; i<object.list.children.length; i++){
					var obj = object.list.children[i];
					store.add(new Ext.data.Record({
						id: obj.id,
						user: obj.login,
						create: obj.isCreate=='true',
						edit: obj.isEdit=='true',
						"delete": obj.isDelete=='true'
					}));
				}
				grid.getSelectionModel().selectFirstRow();
			}
		})
	}
	
	var store = new Ext.data.SimpleStore({
		fields: [
			{name: 'id'},
			{name: 'user'},
			{name: 'create'},
			{name: 'edit'},
			{name: 'delete'}
		]
	});
	
	var userRenderer = function(value, meta, record){
		var res = 'User: '+value;
		if(record.get('create'))
			res += '<img src="im/action/add.png"/>';
		if(record.get('edit'))
			res += '<img src="im/action/edit.png"/>';
		if(record.get('delete'))
			res += '<img src="im/action/remove.png"/>';
		return res;
	
	}
	
	var grid = new Ext.grid.GridPanel({
		store: store,
		title:'Existing permissions:',
		tbar:[
			{
				text:'Remove selected',
				iconCls: 'archive',
				handler: function(){
					if(grid.getSelectionModel().getSelected()){
						callAPI('permission.RemovePermission', {
							noteid: noteid,
							permissionid: grid.getSelectionModel().getSelected().get('id')
						}, function(){
							refreshList();
						})
					}
				}
			}
		],
		columns: [
			{id: 'first', header: 'Permission', dataIndex: 'user', renderer: userRenderer}
		],
		autoExpandColumn: 'first',
		region: 'center'
	});
	
	var createField = new Ext.form.Checkbox({
		xtype: 'checkbox',
		name: 'create',
		boxLabel: 'Create'
		
	});
	
	var editField = new Ext.form.Checkbox({
		xtype: 'checkbox',
		name: 'edit',
		boxLabel: 'Edit'
		
	});
	
	var deleteField = new Ext.form.Checkbox({
		xtype: 'checkbox',
		name: 'delete',
		boxLabel: 'Delete'
		
	});
	
	var form = new Ext.form.FormPanel({
		frame: true,
		defaults: {width: '100%'},
		defaultType: 'textfield',
		labelAlign: 'right',
		region: 'south',
		autoHeight: true,
		title: 'Add new permission:',
		items:[
			{
				fieldLabel: 'User',
				name: 'user'
			},
			{
				xtype:'checkboxgroup',
				fieldLabel: 'Permissions',
				items: [
					createField, editField, deleteField
				]
			}
		],
		buttons: [
			{
				text: 'Add',
				handler: function(){
					var f = form.getForm();
					callAPI('permission.AddPermission', {
						noteid: noteid,
						user: f.findField('user').getValue(),
						is_create: createField.getValue(),
						is_edit: editField.getValue(),
						is_delete: deleteField.getValue()
					}, function(obj){
						f.reset();
						refreshList();
					});
				}
			}
		]
	});
	
	var win = new Ext.Window({
		width: 350,
		height: getWindowHeight(),
		title: 'Modify permisssions:',
		modal: true,
		layout: 'border',
		items: [
			grid, form
		]
	});
	win.on('close', function(){
		setTitle(note.text);
	})
	setTitle('Permissions');
	win.show();
	refreshList();
};

var AGENDA_TYPE_AGENDA = 0;
var AGENDA_TYPE_CALENDAR = 1;
var iAgendaType = AGENDA_TYPE_AGENDA;

var showAgenda = function(callee){
	
	var ELEMENTS_TO_SKIP = 6;
	
	var refreshList = function(sendTags){
		store.removeAll();
		
		//Clear tags
		var tagsString = '';
		if(!sendTags){
			for(var i = ELEMENTS_TO_SKIP; i < agendaToolbar.items.getCount();){
				var item = agendaToolbar.items.itemAt(i);
				agendaToolbar.items.removeAt(i);
				item.destroy();
			}			
		}else{
			//Check all tag buttons
			for(var i = ELEMENTS_TO_SKIP+2; i < agendaToolbar.items.getCount();i++){
				var item = agendaToolbar.items.itemAt(i);
				if(item.pressed){
					if(tagsString!='')
						tagsString += ',';
					tagsString += item.getText();
				}
			}
			
		}
		
		//Clear tags
		
		var dt = new Date();
		
		var dt2 = daysField.getValue()?daysField.getValue():dt;
		
		var year = parseInt(dt.format('Y'));
		var year2 = parseInt(dt2.format('Y'));
		var day = parseInt(dt.format('z'));
		var day2 = parseInt(dt2.format('z'));
		
		var daysBetween = day2-day;
		
		if(year!=year2){
			daysBetween = (dt.isLeapYear()?366:365)-day+(year2-year-1)*365+day2;
		}
		
		var lISODate = '';
		if(iAgendaType==AGENDA_TYPE_CALENDAR){
			lISODate = lDatePicker.getValue().format('Y-m-d');
		}
		
		if(daysBetween<0)
			daysBetween = 0;
		callAPI('agenda.GetAgenda', {
			noteid: note.id,
			appendpaths: 'true',
			addtags: 'true',
			calendar: iAgendaType==AGENDA_TYPE_CALENDAR?'true':'false',
			calendardate: lISODate,
			object:{
				filter:{
					tagsfilter: tagsString
				}
			},
			nextdays: daysBetween
		}, function(object){
			var tags = [];
			var events = [];
			if(object.list.children){
				for(var i = 0; i<object.list.children.length; i++){
					var obj = object.list.children[i];
					if(obj.nodeName=='tag'){
						tags[tags.length] = obj.name;
						continue;
					}
					var crumb = '&nbsp;';
					var lbIsCalendarEvent = obj.nodeName=='event' && iAgendaType==AGENDA_TYPE_CALENDAR;
					if(obj.children){
						for(var j = 0; j<obj.children.length; j++){
							var p = obj.children[j];
							if(j>0)
								crumb += ' &gt; ';
							crumb += '<a href="javascript:;" onclick="selectNote('+p.id+'); agendaWin.close(); return false;" class="crumb" style="'+(lbIsCalendarEvent?'color: #ffffff;':'')+'">'+escapeHTML(p.text)+'</a>';
						}
					}
					if(lbIsCalendarEvent){
						events[events.length] = {
							id: obj.id,
							start: parseInt(obj.start),
							duration: parseInt(obj.duration),
							text: obj.text,
							dates: obj.eventDates,
							crumb: crumb
						};
					}else{
						store.add(new Ext.data.Record({
							id: obj.id,
							selectable: obj.type=='3',
							name: obj.text,
							crumb: crumb,
							icon: obj.icon,
							add_icon: obj.add_icon,
							urgent: obj.urgent,
							recInfo: obj.recurrenceInfo,
							dates: obj.dates
						}));
					}
				}
				if(!sendTags && tags.length>0){
					//Create tag buttons
					agendaToolbar.add('-', 'Tags:');
					for(var i = 0; i< tags.length; i++){
						agendaToolbar.add({
							text: escapeHTML(tags[i]),
							iconCls: 'tag',
							enableToggle: true,
							handler: function(){
								refreshList(true);
							}
						});
					}
				}
//				grid.getSelectionModel().selectFirstRow();
			}
			//Scroll to first row
			grid.getView().focusRow(0);
			if(iAgendaType==AGENDA_TYPE_CALENDAR){
				calendarDayPanel.setEvents(events);
				calendarDayPanel.redrawEvents();
//				calendarDayPanel.scrollToFirstEvent();
				lCalendarDayWrapper.body.scrollTo('top', Math.floor(calendarDayPanel.firstEvent/2), true);
			}
		})
	}
	
	var store = new Ext.data.SimpleStore({
		fields: [
			{name: 'id'},
			{name: 'selectable'},
			{name: 'name'},
			{name: 'icon'},
			{name: 'crumb'},
			{name: 'add_icon'},
			{name: 'urgent'},
			{name: 'dates'},
			{name: 'recInfo'},
			{name: 'checked'}
		]
	});
	
	var nameRenderer = function(value, meta, record){
		var res = '';
		res += '<img src="im/types/p'+record.get('icon')+'.png" class="png_img"/>';
		if(record.get('add_icon'))
			res += '&nbsp;<img src="im/'+record.get('add_icon')+'" class="png_img"/>';
		res += '<span class="link_text">'+value+'</span>';
		if(record.get('crumb'))
			res += '<div class="crumb">'+record.get('crumb')+'</div>';
		return '<div>'+res+'</div>';
	
	}
	
	var datesRenderer = function(value, meta, record){
		var res = '';
		if(value){
			if(iAgendaType==AGENDA_TYPE_CALENDAR){
				res += record.get('recInfo');
			}else{
				res += '<div class="urgent'+record.get('urgent')+' link_text" style="padding-top: 3px; padding-left: 0px;">'+value+'</div>'+record.get('recInfo');			
			}
		}
		return res;
	
	}
	
	var taskSelector = new Ext.grid.TaskSelectionModel({
		dataIndex: 'checked',
		singleSelect: true
	});
	
	var dt = new Date();
	dt = dt.add(Date.DAY, 2);
	
	var daysField = new Ext.form.DateField({
		format: dateFormat,
		value: dt
	});
	
	var refreshButton = new Ext.Toolbar.Button({
		iconCls: 'refresh',
		text: 'Reload',
		handler: function(){
			refreshList();
		}
	});
	
	var switchAgendaType = function(aType){
		lSelectAgendaButton.toggle(aType==AGENDA_TYPE_AGENDA);
		lSelectCalendarButton.toggle(aType!=AGENDA_TYPE_AGENDA);
		daysField.setVisible(aType==AGENDA_TYPE_AGENDA);
		lBeforeDateText.setVisible(aType==AGENDA_TYPE_AGENDA);
//		lCalendarFrame.setVisible(aType!=AGENDA_TYPE_AGENDA);
		
		if(aType==AGENDA_TYPE_AGENDA){
			lCalendarFrame.hide();
		}else{
			lCalendarFrame.show();
			var lDate = new Date();
			lDatePicker.setMinDate(lDate);
			lDatePicker.setValue(lDate);
			calendarDayPanel.setEvents([]);
		}
		iAgendaType = aType;
		agendaWin.doLayout();
		refreshList();
	}
	
	var lSelectAgendaButton = new Ext.Toolbar.Button({
		text: 'List',
		iconCls: 'agenda',
		enableToggle: true,
		pressed: iAgendaType==AGENDA_TYPE_AGENDA,
		handler: function(){
			switchAgendaType(this.pressed?AGENDA_TYPE_AGENDA:AGENDA_TYPE_CALENDAR);
		}
	});
	
	var lSelectCalendarButton = new Ext.Toolbar.Button({
		text: 'Calendar',
		iconCls: 'calendar_btn',
		enableToggle: true,
		pressed: iAgendaType==AGENDA_TYPE_CALENDAR,
		handler: function(){
			switchAgendaType(this.pressed?AGENDA_TYPE_CALENDAR:AGENDA_TYPE_AGENDA);
		}
	});
	
	var lBeforeDateText = new Ext.Toolbar.TextItem('Display from today to');
	var agendaToolbar = new Ext.Toolbar({
		items:[
			lSelectAgendaButton, lSelectCalendarButton, '-',
			lBeforeDateText,  daysField, refreshButton
		]
	});
	
	var calendarDayPanel = new Ext.CalendarDayPanel({
		region: 'center',
		eventDblClick : function(evt, element, config){
			selectNote(config.eventReference.id);
			agendaWin.close();
			return false;
		}
	});
	
	var lDatePicker = new Ext.DatePicker({
		style: 'border-width: 0px; width: 100%;'
	});
	
	lDatePicker.on('select', function(){
		refreshList();
	});
	
	var lCalendarPanel = new Ext.Panel({
		region: 'west',
		width: 175,
		baseCls: 'cal_panel',
		items: lDatePicker
	});
	
	var lCalendarDayWrapper = new Ext.Panel({
		autoScroll: true,
		region: 'center',
		items: calendarDayPanel
	})
	
	var liAgendaWinHeight = getWindowHeight(800, 100);
	
	var lCalendarFrame = new Ext.Panel({
		layout: 'border',
		border: false,
		hideCollapseTool: true,
		collapsible: false,
		region: 'south',
		split: true,
		height: Math.floor(liAgendaWinHeight*0.5),
		items:[lCalendarPanel, lCalendarDayWrapper]
	});
	
	lCalendarDayWrapper.on('resize', function(){
		calendarDayPanel.redrawEvents();
	});
	
	var grid = new Ext.grid.GridPanel({
		store: store,
		region: 'center',
		tbar: agendaToolbar,
		cm: new Ext.grid.ColumnModel([
			taskSelector,
			{id: 'first', header: 'Name', dataIndex: 'name', sortable: false, menuDisabled:true, renderer: nameRenderer, width: 370},
			{id: 'second', header: 'Date', dataIndex: 'dates', sortable: false, menuDisabled:true, width: 230, renderer: datesRenderer}
		]),
		sm: taskSelector,
		viewConfig: {
            forceFit:true
        },
		autoExpandColumn: 'first'
	});
	
	grid.on('rowdblclick', function(grid, row, event){
		selectNote(store.getAt(row).get('id'));
		agendaWin.close();
	});
	
	agendaWin = new Ext.Window({
		width: mainPanel.getSize().width<800?(mainPanel.getSize().width-100):700,
		height: getWindowHeight(800, 100),
		title: 'Agenda:',
		modal: true,
		layout: 'border',
		items: [
			grid, lCalendarFrame
		],
		buttonAlign: 'center',
		buttons: [{
			text: 'Save',
			handler: function(){
				var ids = '';
				store.each(function(record){
					if(record.get('checked')){
						if(ids!='')
							ids += ',';
						ids += record.get('id');
					}
				});
				if(ids=='')
					return;
				callAPI('agenda.CompleteTasks', {
					noteids: ids
				}, function(object){
					refreshList(true);
					refreshNote(note.id, note.id);
				});
			}
		}]
	});
	agendaWin.on('show', function(){
		switchAgendaType(iAgendaType);
//		calendarDayPanel.redrawEvents();
	});
//	refreshList();
	agendaWin.show();
};

var editNote = function(note, newNote, refreshNote, refreshStars, el, forceNewType, newType){
	
	var formLabel = 'Edit ';
	if(newNote)
		formLabel = 'New ';
	var noteType = parseInt(note.type);
	var noteIcon =parseInt(note.customIcon);
	if(forceNewType){
		//Changing type...
		if(newType==TYPE_EVENT){
			var oldDate = Date.parseDate(note.startDate, 'Y-m-d\\TH:i:s');
			if(noteType==TYPE_TASK && oldDate){
				oldDate = oldDate.format('Y-m-d');
				var dt = new Date();
				var mins = parseInt(dt.format('i'));
				if(mins>0){
					dt = dt.add(Date.MINUTE, -mins);
					dt = dt.add(Date.HOUR, 1);
				}
				note.startDate = oldDate+'T'+dt.format('H:i:s');
				dt = dt.add(Date.HOUR, 1);
				note.endDate = oldDate+'T'+dt.format('H:i:s');
			}else{
				note.startDate = null;
				note.endDate = null;
			}
		}
		if(noteIcon==noteType)
			noteIcon = newType;
		noteType = newType;
	}
	
	var text = new Ext.form.TextField(
		{
			fieldLabel: 'Name',
			allowBlank: false,
			name: 'name',
			enableKeyEvents: true,
			anchor: '99%'
		}
	);
	
	if(newNote){
		text.on('keydown', function(item, event){
			if(event.getKey()==Ext.EventObject.ENTER){
				if(form.getForm().isValid()){
					sendNote();
				}				
			}
		});
	}
	
	var url = new Ext.form.TextField(
		{
			fieldLabel: 'URL',
			allowBlank: false,
			name: 'url',
			anchor: '99%',
			value: note.url
		}
	);
	
	var textContent = new Ext.form.TextArea({
			fieldLabel: 'Description',
			name: 'textContent',
			cls: 'fixed-font',
			height: '200',
			anchor: '99%',
			value: note.textContent
	});
	
	var uploadField = new Ext.form.FileUploadField({
			fieldLabel: 'File (5 MB max)',
			anchor: '99%',
			allowBlank: !newNote,
			name: 'file'
	});
	
	var tags = new Ext.form.TextField(
		{
			fieldLabel: 'Tags',
			name: 'tags',
			anchor: '99%',
			value: note.tags
		}
	);
	var pr = parseInt(newNote?2:note.priority);
	if(pr>2 || pr<0)
		pr = 2;
	var priority = new Ext.form.RadioGroup({
		anchor: '99%',
		fieldLabel: 'Priority',
		autoHeight: true,
		defaultType: 'radio',
		allowBlank: false,
		columns: [40, 40, 40],
		vertical: true,
		defaults:{
			border: false
		},
		items:[
			{
				boxLabel: '<img src="im/priority/p0.png"/>',
				name: 'priority',
				checked: pr==0,
//				width: 60,
				inputValue: 0
			},
			{
				boxLabel: '<img src="im/priority/p1.png"/>',
				name: 'priority',
				checked: pr==1,
				inputValue: 1
			},
			{
				boxLabel: '<img src="im/priority/p2.png"/>',
				name: 'priority',
				checked: pr==2,
				inputValue: 2
			}
		]
	});
	
	var completed = new Ext.form.Checkbox({
		name: 'completed',
		checked: note.completed=='true',
		value: 'true',
		inputValue: 'true',
		fieldLabel: 'Completed'
	});
	
//		format: user.dateFormat
	var dueDate = new Ext.form.DateField({
		anchor: '30%',
		format: dateFormat,
		fieldLabel: 'Due date'
	});
	
	var startDateField = new Ext.form.DateField({
		anchor: '100%',
		format: dateFormat,
		fieldLabel: 'Date started'
	});
	
	var endDateField = new Ext.form.DateField({
		anchor: '100%',
		format: dateFormat,
		fieldLabel: 'Date finished'
	});
	
	var startTimeField = new Ext.form.TimeField({
		anchor: '100%',
		format: timeFormat,
		allowBlank: false,
		fieldLabel: 'Time started'
	});
	
	var endTimeField = new Ext.form.TimeField({
		anchor: '100%',
		format: timeFormat,
		allowBlank: false,
		fieldLabel: 'Time finished'
	});
	
	var icn = new Ext.IconField({});
	var icn2 = new Ext.IconField({
		selected: true
	});
	
	var changeIcon = null;
	
	var createIconToolbar = function(icns){
		var icons = [];
//		var colSizes = [];
		for(var i = 0; i<icns; i++){
			var icon = new Ext.IconField({
				selected: i==noteIcon,
				icon: 'im/types/p'+i+'.png',
				iconCls: 'img_png',
				value: i
			});
			icon.on('selected', function(){
				for(var i = 0; i<icns; i++){
					if(i!=this.value)
						icons[i].setSelected(false);
				}
				noteIcon = this.value;
			});
			icons[icons.length] = icon;
//			if(i<32)
//				colSizes[colSizes.length] = 22;
		}
		changeIcon = new Ext.form.FieldSet({
			layout: 'table',
			collapsible: true,
			collapsed: true,
			autoHeight: true,
			title: 'Change icon:',
			layoutConfig: {
				columns: 30
			},
			items: icons
		});
		
	};
	
	createIconToolbar(39);
	
	var lrType = '';
	var lrDays = 1;
	var lrPeriod = 'days';
	
	var rArray = [];
	if(note.recurrence){
		rArray = note.recurrence.split('_');
		lrType = rArray.length>0?rArray[0]:'repeat';
		lrDays = rArray.length>1?parseInt(rArray[1]):1;
		lrPeriod = rArray.length>2?rArray[2]:'days';
	}
	
	var repeatType = new Ext.form.ComboBox({
		fieldLabel: 'Recurrence',
		store: new Ext.data.SimpleStore({
			fields: ['id', 'name'],
			data: [
				["", "No recurrence"],
				["repeat", "Repeat every"],
				["after", "Repeat after"]
			]
		}),
		displayField: 'name',
		valueField: 'id',
		forceSelection: true,
		triggerAction: 'all',
		selectOnFocus:true,
		editable: false,
		mode: 'local',
		value: lrType,
		width: 120
	});
	
	var repeatDays = new Ext.form.NumberField({
		value: lrDays,
		minValue: 1,
		maxValue: 365,
		width: 45
	});
	
	var repeatPeriod = new Ext.form.ComboBox({
		store: new Ext.data.SimpleStore({
			fields: ['id', 'name'],
			data: [
				["days", "day(s)"],
				["weeks", "week(s)"],
				["months", "month(s)"],
				["years", "years(s)"]
			]
		}),
		displayField: 'name',
		valueField: 'id',
		forceSelection: true,
		triggerAction: 'all',
		selectOnFocus:true,
		editable: false,
		mode: 'local',
		value: lrPeriod,
		width: 90
	});
	
	if(!lrType){
		repeatDays.setDisabled(true);
		repeatPeriod.setDisabled(true);		
	}
	
	repeatType.on('beforeselect', function(combo, record, index){
		if(index>0){
			repeatDays.setDisabled(false);
			repeatPeriod.setDisabled(false);
		}else{
			repeatDays.setDisabled(true);
			repeatPeriod.setDisabled(true);			
		}
	});
	
	var recurrenceBar = new Ext.form.FieldSet({
		layout: 'column',
		style: 'padding: 0px; border: none; margin-top: 10px;',
		autoHeight: true,
		items:[
			{
				width: 230,
				layout: 'form',
				items:repeatType
			},{
				width: 50,
				items:repeatDays
			},{
				width: 100,
				layout: 'fit',
				items:repeatPeriod
			}
		]
	});
	
	var dateTimes = new Ext.form.FieldSet({
		anchor: '99%',
		layout: 'column',
		style: 'padding: 0px; border: none; margin-top: 10px;',
		autoHeight: true,
		items:[
			{
				columnWidth: 0.5,
				layout: 'form',
				items:[
					startDateField, endDateField
				]
			},{
				columnWidth: 0.5,
				layout: 'form',
				items:[
					startTimeField, endTimeField
				]
			}
		]
	});
	
	var tokenField = new Ext.form.Hidden({
		name: 'token',
		value: token
	});
	
	var jsonField = new Ext.form.Hidden({
		name: 'json',
		value: 'true'
	});
	
	var iconField = new Ext.form.Hidden({
		name: 'customIcon'
	});
	
	var idField = new Ext.form.Hidden({
		name: 'id',
		value: note.id
	});
	
	var typeField = new Ext.form.Hidden({
		name: 'type',
		value: noteType
	});
	
	var recurrenceField = new Ext.form.Hidden({
		name: 'recurrence',
		value: ''
	});
	
	var randomField = new Ext.form.Hidden({
		name: 'rnd',
		value: generateRandomString(20)
	});
	
	var newField = new Ext.form.Hidden({
		name: 'newNote',
		value: newNote
	});
	
	var startDateHiddenField = new Ext.form.Hidden({
		name: 'startDate',
		value: 'true'
	});
	
	var endDateHiddenField = new Ext.form.Hidden({
		name: 'endDate',
		value: 'true'
	});
	
	var startDate = Date.parseDate(note.startDate, "Y-m-d\\TH:i:s");
	var endDate = Date.parseDate(note.endDate, "Y-m-d\\TH:i:s");
	var items = null;
	var formHeight = 400;
	var focusedField = text;
	
	var winFixedHeight = false;
	
	var textAreaHeight = 0;
	
	switch(noteType){
		case TYPE_TEXT:
			formLabel += 'text note';
			textAreaHeight = 250;
			items = [changeIcon, text, textContent, tags, jsonField];
			if(!newNote)
				focusedField = textContent;
			break;
		case TYPE_IMAGE:
			winFixedHeight = true;
			formLabel += 'image';
			items = [changeIcon, text, uploadField, tags];
			break;
		case TYPE_AUDIO:
			formLabel += 'audio note';
			break;
		case TYPE_TASK:
			formLabel += 'task';
			textAreaHeight = 150;
			dueDate.setValue(startDate);
			items = [changeIcon, text, priority, completed, dueDate, recurrenceBar, textContent, tags, startDateHiddenField, recurrenceField];
			if(!newNote)
				focusedField = textContent;
			break;
		case TYPE_EVENT:
			textAreaHeight = 160;
			formLabel += 'event';
			var dt = new Date();
			var mins = parseInt(dt.format('i'));
			if(mins>0){
				dt = dt.add(Date.MINUTE, -mins);
				dt = dt.add(Date.HOUR, 1);
			}
			if(startDate){
				startDateField.setValue(startDate);
				startTimeField.setValue(startDate);
			}else{
				//Default dates
				startDateField.setValue(dt);				
				startTimeField.setValue(dt);
			}
			if(endDate){
				endDateField.setValue(endDate);
				endTimeField.setValue(endDate);
			}else{
				dt = dt.add(Date.HOUR, 1);
				endDateField.setValue(dt);				
				endTimeField.setValue(dt);
			}
			items = [changeIcon, text, dateTimes, recurrenceBar, textContent, tags, startDateHiddenField, endDateHiddenField, recurrenceField];
			if(!newNote)
				focusedField = textContent;
			break;
		case TYPE_BMARK:
			formLabel += 'bookmark';
			items = [changeIcon, text, url, textContent, tags];
			textAreaHeight = 220;
			if(!newNote)
				focusedField = textContent;
			break;
		case TYPE_FILE:
			winFixedHeight = true;
			formLabel += 'file';
			items = [changeIcon, text, uploadField, tags];
			break;
	}
	
	var okHeight = getWindowHeight();
	textAreaHeight += (okHeight-425);
	
	textContent.setHeight(textAreaHeight);
	//Text note: 423, task: 421, event: 421, bmark: 399
	items[items.length] = idField;
	items[items.length] = jsonField;
	items[items.length] = tokenField;
	items[items.length] = randomField;
	items[items.length] = newField;
	items[items.length] = iconField;
	items[items.length] = typeField;
	
	var sendNote = function(){
		if(!text.getValue()){
			showError('Name should be filled');
			return;
		}
		randomField.setValue(generateRandomString(20));
		
		if(repeatType.getValue()){
			recurrenceField.setValue(repeatType.getValue()+'_'+repeatDays.getValue()+'_'+repeatPeriod.getValue());
		}else{
			recurrenceField.setValue('');
		}
		switch(noteType){
			case TYPE_TASK:				
				startDateHiddenField.setValue(dueDate.getValue()?dueDate.getValue().format('Y-m-d')+'T12:00:00':null);
				break;
			case TYPE_EVENT:
				if(startDateField.getValue()){
					var d = startDateField.getValue().format('Y-m-d\\T')+startTimeField.getValue();
					d = Date.parseDate(d, 'Y-m-d\\T'+timeFormat);
					if(d)
						startDateHiddenField.setValue(d.format('Y-m-d\\TH:i:s'));
				}
				
				note.endDate = null;
				if(endDateField.getValue()){
					var d = endDateField.getValue().format('Y-m-d\\T')+endTimeField.getValue();
					d = Date.parseDate(d, 'Y-m-d\\T'+timeFormat);
					if(d)
						endDateHiddenField.setValue(d.format('Y-m-d\\TH:i:s'));
				}
				
				break;
		}
		
		iconField.setValue(noteIcon);
		startNetwork();
		form.getForm().submit();
		
	}
	
	text.setValue(newNote?formLabel:note.text);
	var form = new Ext.form.FormPanel({
		frame: true,
		url: APIURL+'/api/SaveNote',
		fileUpload: true,
		defaultType: 'textfield',
		labelAlign: 'right',
		autoHeight: true,
		items: items,
		buttons:[
			{
				text: 'Save',
				handler: function(){
					if(form.getForm().isValid()){
						sendNote();
					}
				}
			}
		]
	});
	
	var closeWin = function(id1, id2){
			win.close();
			refreshNote(id1, id2);
			if(refreshStars)
				refreshStars();			
	}

	form.getForm().on('actioncomplete', function(f, action){
		endNetwork();
		callAPI('CheckSaveResult', {
			rnd: randomField.getValue()
		}, function(object){
			closeWin(note.id, object.note.id);
		})
	});
	
	var okWidth = mainPanel.getSize().width<800?Math.round(mainPanel.getSize().width*0.8):700;
	
	var win = new Ext.Window({
		width: okWidth,
		autoHeight: true,
		title: formLabel+':',
		fileUpload: true,
		modal: true,
		layout: 'fit',
		items: form,
		onEsc: function(){
			//Think about escape
		}
	});
	win.on('show', function(){
		focusedField.focus(newNote, 10);
	});
	win.on('close', function(){
		setTitle(note.text);
	})
	setTitle(newNote?formLabel:note.text);
	win.show();
};

var regUser = function(){
	var minuteOffset = new Ext.form.ComboBox({
		fieldLabel: 'Time zone',
		store: new Ext.data.SimpleStore({
			fields: ['id', 'name'],
			data: tz
		}),
		displayField: 'name',
		valueField: 'id',
		forceSelection: true,
		triggerAction: 'all',
		selectOnFocus:true,
		editable: false,
		mode: 'local',
		value: 'GMT'
	});
	
	var server = new Ext.form.TextField({
		fieldLabel: 'Server',
		value: DEFAULT_SERVER,
//		msgTarget: 'under',
		allowBlank: false
	});
	
	var login = new Ext.form.TextField({
		fieldLabel: 'Login name',
//		msgTarget: 'under',
		allowBlank: false
	});
	
	var name = new Ext.form.TextField({
		fieldLabel: 'Name',
//		msgTarget: 'under',
		allowBlank: false
	});
	
	var email = new Ext.form.TextField({
//		msgTarget: 'under',
		fieldLabel: 'E-mail'
	});
	
	var password = new Ext.form.TextField({
		fieldLabel: 'Password',
		allowBlank: false,
//		msgTarget: 'under',
		inputType: 'password'
	});
	
	var password2 = new Ext.form.TextField({
		fieldLabel: 'Retype password',
		allowBlank: false,
//		msgTarget: 'under',
		inputType: 'password'
	});
	
	var regForm = new Ext.FormPanel({
		frame: true,
		defaults: {width: '100%'},
		autoHeight: true,
//		autoWidth: true,
		defaultType: 'textfield',
		labelAlign: 'right',
		items: [
			server, login, name, email, minuteOffset, password, password2
		],
		buttons: [
			{
				text: 'Submit',
				handler: function(){
					var form = regForm.getForm();
					if(!form.isValid())
						return;
					var user = new Object();
					user.login = login.getValue();
					user.name = name.getValue();
					user.email = email.getValue();
					user.timeZone = minuteOffset.getValue();
					user.password = password.getValue();
					if(user.password!=password2.getValue()){
//						showError('Passwords don\'t match');
						password2.markInvalid('Passwords don\'t match');
						return;
					}
					APIURL = 'http://'+server.getValue();
					SERVERURL = server.getValue();
					callAPI('user.RegisterUser', {
						object: {
							user: user
						}
					}, function(object){
						showInfo('User registered');
						win.close();
					})
				}
			}
		]
	});
	
	var win = new Ext.Window({
		width: 500,
		plain: true,
		autoHeight: true,
		title: 'New user registration:',
		modal: true,
		layout: 'fit',
		items: regForm,
		onEsc: function(){
			//Think about escape
		}
	});
	
	win.on('show', function(){
		setTitle('New user');
		var form = regForm.getForm();
		form.isValid();
		login.focus(false, 10);
	});
	win.on('close', function(){
		setTitle('Login');
	});
	win.show();
};

Ext.onReady(function() {
	Ext.QuickTips.init();
	var d = new Date();
	d = d.add(Date.YEAR, 30);
	var provider = new Ext.state.CookieProvider({
		expires: d
	});
	
	var arr = provider.get('sessions', []);
//	var arr = [];
	for (var i=0; i < arr.length; i++) {
		if(!arr[i]){
			arr.splice(i, 1);
			i--;
		}
	};
	
	var sessionStore = new Ext.data.SimpleStore({
		fields: ['login', 'server', 'token', 'save_pass'],
		data: arr
	});
	var lShowGrid = sessionStore.getCount()>0;
	
	if(lShowGrid){
		var selection = new Ext.grid.RowSelectionModel({singleSelect:true});
		var toolbar = new Ext.Toolbar({
			items:[{
				text:'Login',
				iconCls: 'login',
				handler: function(){
					var record = sessionGrid.getSelectionModel().getSelected();
					if(record){
						var login = record.get('login');
						var server = record.get('server');
						var token = record.get('token');
						var lSavePassword = record.get('save_pass');
						doLogin(login, server, token, lSavePassword);
					}
				}
			}, {
				text:'Remove',
				iconCls: 'archive',
				handler: function(){
					var record = sessionGrid.getSelectionModel().getSelected();
					if(record){
						for (var i=0; i < arr.length; i++) {
							var item = arr[i];
							if(item[0]==record.get('login') && item[1]==record.get('server')){
								sessionStore.remove(record);
								arr.splice(i, 1);
								provider.set('sessions', arr);
								selection.selectFirstRow();
	//							toolbar.setVisible(arr.length>0);
								return;
							}
						}
					}
				}
			}]
		});
		var sessionGrid = new Ext.grid.GridPanel({
			sm: selection,
			tbar: arr.length>0? toolbar : null,
			region: 'center',
			title: 'Saved sessions:',
			store: sessionStore,
			columns: [
				{id: 'first', header: 'Server', dataIndex: 'server', sortable: true},
				{header: 'Login', dataIndex: 'login', sortable: true, align: 'right'}
			],
			autoExpandColumn: 'first',
	//		height: 200,
			border: false
		});
		
		sessionGrid.on('rowdblclick', function(){
			var record = sessionGrid.getSelectionModel().getSelected();
			if(record){
				var login = record.get('login');
				var server = record.get('server');
				var token = record.get('token');
				var lSavePassword = record.get('save_pass');
				doLogin(login, server, token, lSavePassword);
			}
		});
		
	}
	
	var rememberMe = new Ext.form.Checkbox({
		fieldLabel: 'Remember me'
	});
	
	var savePassword = new Ext.form.Checkbox({
		fieldLabel: 'Save password'
	});
	
	var doLogin = function(login, server, tok, aSavePassword){
		if(!tok || ''==tok){
			
			var lPasswordField = new Ext.form.TextField({
				anchor: '100%',
				inputType: 'password',
				value: '',
				name: 'password',
				enableKeyEvents: true
			});
			
			lPasswordField.on('keydown', function(item, event){
				if(event.getKey()==Ext.EventObject.ENTER){
					doLoginWithPassword();
				}
			});
			var doLoginWithPassword = function(){
				APIURL = 'http://'+server;
				SERVERURL = server;
				var password = hex_md5(lPasswordField.getValue());
				callAPI('user.CheckUserNamePassword', {
					userName: login,
					password: password
				}, function(object){
					user = object.user;
					token = user.token;
					lPasswordWindow.close();
					win.close();
					statusString = 'Connected to: '+login+'@'+server;
					mainForm();
				}, function(){
					lPasswordField.setValue('');
					lPasswordField.focus(true, 10);
				});
			}
			
			var lPasswordWindow = new Ext.Window({
				width: 200,
				autoHeight: true,
				plain: true,
				modal: true,
				title: 'Enter password:',
				layout: 'fit',
				buttonAlign: 'center',
				items: lPasswordField,
				buttons: [{
					text: 'Ok',
					handler: function(){
						doLoginWithPassword();
					}
				}]
			});
			
			lPasswordWindow.on('show', function(){
				lPasswordField.focus(true, 10);
			});
			lPasswordWindow.show();
			
			return;
		}
		APIURL = 'http://'+server;
		SERVERURL = server;
		token = tok;
		callAPI('user.GetCurrentUser', {}, function(object){
			user = object.user;
			win.close();
			statusString = 'Connected to: '+login+'@'+server;
			mainForm();
		});
		
	}
	
	var saveSession = function(login, server, token, aSavePassword){
		for(var i = 0; i<arr.length; i++){
			var item = arr[i];
			if(item[0]==login && item[1]==server){
				item[2] = aSavePassword?token:'';
				item[3] = aSavePassword;
				provider.set('sessions', arr);
				return;
			}
		}
		arr[arr.length] = [login, server, aSavePassword?token:'', aSavePassword];
		provider.set('sessions', arr);
	}
	
	var iLoginField = new Ext.form.TextField({
		fieldLabel: 'Login name',
		anchor: '100%',
		value: '',
		name: 'login',
		enableKeyEvents: true
	});
	
	iLoginField.on('keydown', function(item, event){
		if(event.getKey()==Ext.EventObject.ENTER){
			iPasswordField.focus();
		}
	});
	
	var iPasswordField = new Ext.form.TextField({
		fieldLabel: 'Password',
		anchor: '100%',
		inputType: 'password',
		value: '',
		name: 'password',
		enableKeyEvents: true
	});
	
	iPasswordField.on('keydown', function(item, event){
		if(event.getKey()==Ext.EventObject.ENTER){
			doMainLogin();
		}
	});
	
	var doMainLogin = function(){
		var server = loginForm.getForm().findField('server').getValue();
		var login = loginForm.getForm().findField('login').getValue();
		APIURL = 'http://'+server;
		SERVERURL = server;
		var password = hex_md5(loginForm.getForm().findField('password').getValue());
		callAPI('user.CheckUserNamePassword', {
			userName: login,
			password: password
		}, function(object){
			user = object.user;
			token = user.token;
			win.close();
			if(rememberMe.getValue()){
				saveSession(login, server, token, savePassword.getValue());
			}
			statusString = 'Connected to: '+login+'@'+server;
			mainForm();
		});		
	}
	
	var loginForm = new Ext.FormPanel({
		frame: true,
		region: lShowGrid?'north':'center',
//		width: 400,
		autoHeight: true,
		minButtonWidth: 90,
		defaultType: 'textfield',
		labelAlign: 'right',
		items: [
			{
				fieldLabel: 'Server',
				anchor: '100%',
				value: DEFAULT_SERVER,
				name: 'server'
			},iLoginField, iPasswordField, rememberMe, savePassword
		],
		buttons: [
			{
				text: 'Login',
				handler: function(){
					doMainLogin();
				}
			},
			{
				text: 'New user',
				width: 100,
				handler: function(){
					regUser();
				}
			}
		]
	});
	
// 	var networkPanel = new Ext.Panel({
// //		contentEl: 'network',
// 		html: 'Loading...',
// 		border: true,
// 		margins: '5 5 5 5',
// 		height: 50
// 	});
// 	
// 	networkPanel.render(Ext.get('network'));
//	networkPanel.slideOut();
	
	var win = new Ext.Window({
//		autoWidth: true,
		width: 350,
		stateful: false,
		autoHeight: !lShowGrid,
		height: 380,
		plain: true,
		title: 'Be Organized! Login:',
		closable: false,
		layout: lShowGrid?'border':'fit',
		items: lShowGrid?[loginForm, sessionGrid]:[loginForm]
	});
	win.on('show', function(){
		document.getElementById('loading').style.display = 'none';
//		setTitle("Login");
		iLoginField.focus(false, 10);
		if(lShowGrid)
			selection.selectFirstRow();
	});
	win.show();
});

var tz = [
['MIT', 'GMT-11 MIT'],
['Pacific/Apia', 'GMT-11 Pacific/Apia'],
['Pacific/Midway', 'GMT-11 Pacific/Midway'],
['Pacific/Niue', 'GMT-11 Pacific/Niue'],
['Pacific/Pago_Pago', 'GMT-11 Pacific/Pago_Pago'],
['Pacific/Samoa', 'GMT-11 Pacific/Samoa'],
['US/Samoa', 'GMT-11 US/Samoa'],
['America/Adak', 'GMT-10/GMT-9 America/Adak'],
['America/Atka', 'GMT-10/GMT-9 America/Atka'],
['HST', 'GMT-10 HST'],
['Pacific/Fakaofo', 'GMT-10 Pacific/Fakaofo'],
['Pacific/Honolulu', 'GMT-10 Pacific/Honolulu'],
['Pacific/Johnston', 'GMT-10 Pacific/Johnston'],
['Pacific/Rarotonga', 'GMT-10 Pacific/Rarotonga'],
['Pacific/Tahiti', 'GMT-10 Pacific/Tahiti'],
['US/Aleutian', 'GMT-10/GMT-9 US/Aleutian'],
['US/Hawaii', 'GMT-10 US/Hawaii'],
['Pacific/Marquesas', 'GMT-9:30 Pacific/Marquesas'],
['AST', 'GMT-9/GMT-8 AST'],
['America/Anchorage', 'GMT-9/GMT-8 America/Anchorage'],
['America/Juneau', 'GMT-9/GMT-8 America/Juneau'],
['America/Nome', 'GMT-9/GMT-8 America/Nome'],
['America/Yakutat', 'GMT-9/GMT-8 America/Yakutat'],
['Pacific/Gambier', 'GMT-9 Pacific/Gambier'],
['US/Alaska', 'GMT-9/GMT-8 US/Alaska'],
['America/Dawson', 'GMT-8/GMT-7 America/Dawson'],
['America/Ensenada', 'GMT-8/GMT-7 America/Ensenada'],
['America/Los_Angeles', 'GMT-8/GMT-7 America/Los_Angeles'],
['America/Tijuana', 'GMT-8/GMT-7 America/Tijuana'],
['America/Vancouver', 'GMT-8/GMT-7 America/Vancouver'],
['America/Whitehorse', 'GMT-8/GMT-7 America/Whitehorse'],
['Canada/Pacific', 'GMT-8/GMT-7 Canada/Pacific'],
['Canada/Yukon', 'GMT-8/GMT-7 Canada/Yukon'],
['Mexico/BajaNorte', 'GMT-8/GMT-7 Mexico/BajaNorte'],
['PST', 'GMT-8/GMT-7 PST'],
['PST8PDT', 'GMT-8/GMT-7 PST8PDT'],
['Pacific/Pitcairn', 'GMT-8 Pacific/Pitcairn'],
['US/Pacific', 'GMT-8/GMT-7 US/Pacific'],
['US/Pacific-New', 'GMT-8/GMT-7 US/Pacific-New'],
['America/Boise', 'GMT-7/GMT-6 America/Boise'],
['America/Cambridge_Bay', 'GMT-7/GMT-6 America/Cambridge_Bay'],
['America/Chihuahua', 'GMT-7/GMT-6 America/Chihuahua'],
['America/Dawson_Creek', 'GMT-7 America/Dawson_Creek'],
['America/Denver', 'GMT-7/GMT-6 America/Denver'],
['America/Edmonton', 'GMT-7/GMT-6 America/Edmonton'],
['America/Hermosillo', 'GMT-7 America/Hermosillo'],
['America/Inuvik', 'GMT-7/GMT-6 America/Inuvik'],
['America/Mazatlan', 'GMT-7/GMT-6 America/Mazatlan'],
['America/Phoenix', 'GMT-7 America/Phoenix'],
['America/Shiprock', 'GMT-7/GMT-6 America/Shiprock'],
['America/Yellowknife', 'GMT-7/GMT-6 America/Yellowknife'],
['Canada/Mountain', 'GMT-7/GMT-6 Canada/Mountain'],
['MST', 'GMT-7 MST'],
['MST7MDT', 'GMT-7/GMT-6 MST7MDT'],
['Mexico/BajaSur', 'GMT-7/GMT-6 Mexico/BajaSur'],
['Navajo', 'GMT-7/GMT-6 Navajo'],
['PNT', 'GMT-7 PNT'],
['US/Arizona', 'GMT-7 US/Arizona'],
['US/Mountain', 'GMT-7/GMT-6 US/Mountain'],
['America/Belize', 'GMT-6 America/Belize'],
['America/Cancun', 'GMT-6/GMT-5 America/Cancun'],
['America/Chicago', 'GMT-6/GMT-5 America/Chicago'],
['America/Costa_Rica', 'GMT-6 America/Costa_Rica'],
['America/El_Salvador', 'GMT-6 America/El_Salvador'],
['America/Guatemala', 'GMT-6 America/Guatemala'],
['America/Indiana/Knox', 'GMT-6/GMT-5 America/Indiana/Knox'],
['America/Indiana/Tell_City', 'GMT-6/GMT-5 America/Indiana/Tell_City'],
['America/Knox_IN', 'GMT-6/GMT-5 America/Knox_IN'],
['America/Managua', 'GMT-6 America/Managua'],
['America/Menominee', 'GMT-6/GMT-5 America/Menominee'],
['America/Merida', 'GMT-6/GMT-5 America/Merida'],
['America/Mexico_City', 'GMT-6/GMT-5 America/Mexico_City'],
['America/Monterrey', 'GMT-6/GMT-5 America/Monterrey'],
['America/North_Dakota/Center', 'GMT-6/GMT-5 America/North_Dakota/Center'],
['America/North_Dakota/New_Salem', 'GMT-6/GMT-5 America/North_Dakota/New_Salem'],
['America/Rainy_River', 'GMT-6/GMT-5 America/Rainy_River'],
['America/Rankin_Inlet', 'GMT-6/GMT-5 America/Rankin_Inlet'],
['America/Regina', 'GMT-6 America/Regina'],
['America/Swift_Current', 'GMT-6 America/Swift_Current'],
['America/Tegucigalpa', 'GMT-6 America/Tegucigalpa'],
['America/Winnipeg', 'GMT-6/GMT-5 America/Winnipeg'],
['CST', 'GMT-6/GMT-5 CST'],
['CST6CDT', 'GMT-6/GMT-5 CST6CDT'],
['Canada/Central', 'GMT-6/GMT-5 Canada/Central'],
['Canada/East-Saskatchewan', 'GMT-6 Canada/East-Saskatchewan'],
['Canada/Saskatchewan', 'GMT-6 Canada/Saskatchewan'],
['Chile/EasterIsland', 'GMT-6/GMT-5 Chile/EasterIsland'],
['Mexico/General', 'GMT-6/GMT-5 Mexico/General'],
['Pacific/Easter', 'GMT-6/GMT-5 Pacific/Easter'],
['Pacific/Galapagos', 'GMT-6 Pacific/Galapagos'],
['US/Central', 'GMT-6/GMT-5 US/Central'],
['US/Indiana-Starke', 'GMT-6/GMT-5 US/Indiana-Starke'],
['America/Atikokan', 'GMT-5 America/Atikokan'],
['America/Bogota', 'GMT-5 America/Bogota'],
['America/Cayman', 'GMT-5 America/Cayman'],
['America/Coral_Harbour', 'GMT-5 America/Coral_Harbour'],
['America/Detroit', 'GMT-5/GMT-4 America/Detroit'],
['America/Eirunepe', 'GMT-5 America/Eirunepe'],
['America/Fort_Wayne', 'GMT-5/GMT-4 America/Fort_Wayne'],
['America/Grand_Turk', 'GMT-5/GMT-4 America/Grand_Turk'],
['America/Guayaquil', 'GMT-5 America/Guayaquil'],
['America/Havana', 'GMT-5/GMT-4 America/Havana'],
['America/Indiana/Indianapolis', 'GMT-5/GMT-4 America/Indiana/Indianapolis'],
['America/Indiana/Marengo', 'GMT-5/GMT-4 America/Indiana/Marengo'],
['America/Indiana/Petersburg', 'GMT-5/GMT-4 America/Indiana/Petersburg'],
['America/Indiana/Vevay', 'GMT-5/GMT-4 America/Indiana/Vevay'],
['America/Indiana/Vincennes', 'GMT-5/GMT-4 America/Indiana/Vincennes'],
['America/Indiana/Winamac', 'GMT-5/GMT-4 America/Indiana/Winamac'],
['America/Indianapolis', 'GMT-5/GMT-4 America/Indianapolis'],
['America/Iqaluit', 'GMT-5/GMT-4 America/Iqaluit'],
['America/Jamaica', 'GMT-5 America/Jamaica'],
['America/Kentucky/Louisville', 'GMT-5/GMT-4 America/Kentucky/Louisville'],
['America/Kentucky/Monticello', 'GMT-5/GMT-4 America/Kentucky/Monticello'],
['America/Lima', 'GMT-5 America/Lima'],
['America/Louisville', 'GMT-5/GMT-4 America/Louisville'],
['America/Montreal', 'GMT-5/GMT-4 America/Montreal'],
['America/Nassau', 'GMT-5/GMT-4 America/Nassau'],
['America/New_York', 'GMT-5/GMT-4 America/New_York'],
['America/Nipigon', 'GMT-5/GMT-4 America/Nipigon'],
['America/Panama', 'GMT-5 America/Panama'],
['America/Pangnirtung', 'GMT-5/GMT-4 America/Pangnirtung'],
['America/Port-au-Prince', 'GMT-5 America/Port-au-Prince'],
['America/Porto_Acre', 'GMT-5 America/Porto_Acre'],
['America/Resolute', 'GMT-5 America/Resolute'],
['America/Rio_Branco', 'GMT-5 America/Rio_Branco'],
['America/Thunder_Bay', 'GMT-5/GMT-4 America/Thunder_Bay'],
['America/Toronto', 'GMT-5/GMT-4 America/Toronto'],
['Brazil/Acre', 'GMT-5 Brazil/Acre'],
['Canada/Eastern', 'GMT-5/GMT-4 Canada/Eastern'],
['Cuba', 'GMT-5/GMT-4 Cuba'],
['EST', 'GMT-5 EST'],
['EST5EDT', 'GMT-5/GMT-4 EST5EDT'],
['IET', 'GMT-5/GMT-4 IET'],
['Jamaica', 'GMT-5 Jamaica'],
['US/East-Indiana', 'GMT-5/GMT-4 US/East-Indiana'],
['US/Eastern', 'GMT-5/GMT-4 US/Eastern'],
['US/Michigan', 'GMT-5/GMT-4 US/Michigan'],
['America/Caracas', 'GMT-4:30 America/Caracas'],
['America/Anguilla', 'GMT-4 America/Anguilla'],
['America/Antigua', 'GMT-4 America/Antigua'],
['America/Aruba', 'GMT-4 America/Aruba'],
['America/Asuncion', 'GMT-4/GMT-3 America/Asuncion'],
['America/Barbados', 'GMT-4 America/Barbados'],
['America/Blanc-Sablon', 'GMT-4 America/Blanc-Sablon'],
['America/Boa_Vista', 'GMT-4 America/Boa_Vista'],
['America/Campo_Grande', 'GMT-4/GMT-3 America/Campo_Grande'],
['America/Cuiaba', 'GMT-4/GMT-3 America/Cuiaba'],
['America/Curacao', 'GMT-4 America/Curacao'],
['America/Dominica', 'GMT-4 America/Dominica'],
['America/Glace_Bay', 'GMT-4/GMT-3 America/Glace_Bay'],
['America/Goose_Bay', 'GMT-4/GMT-3 America/Goose_Bay'],
['America/Grenada', 'GMT-4 America/Grenada'],
['America/Guadeloupe', 'GMT-4 America/Guadeloupe'],
['America/Guyana', 'GMT-4 America/Guyana'],
['America/Halifax', 'GMT-4/GMT-3 America/Halifax'],
['America/La_Paz', 'GMT-4 America/La_Paz'],
['America/Manaus', 'GMT-4 America/Manaus'],
['America/Marigot', 'GMT-4 America/Marigot'],
['America/Martinique', 'GMT-4 America/Martinique'],
['America/Moncton', 'GMT-4/GMT-3 America/Moncton'],
['America/Montserrat', 'GMT-4 America/Montserrat'],
['America/Port_of_Spain', 'GMT-4 America/Port_of_Spain'],
['America/Porto_Velho', 'GMT-4 America/Porto_Velho'],
['America/Puerto_Rico', 'GMT-4 America/Puerto_Rico'],
['America/Santiago', 'GMT-4/GMT-3 America/Santiago'],
['America/Santo_Domingo', 'GMT-4 America/Santo_Domingo'],
['America/St_Barthelemy', 'GMT-4 America/St_Barthelemy'],
['America/St_Kitts', 'GMT-4 America/St_Kitts'],
['America/St_Lucia', 'GMT-4 America/St_Lucia'],
['America/St_Thomas', 'GMT-4 America/St_Thomas'],
['America/St_Vincent', 'GMT-4 America/St_Vincent'],
['America/Thule', 'GMT-4/GMT-3 America/Thule'],
['America/Tortola', 'GMT-4 America/Tortola'],
['America/Virgin', 'GMT-4 America/Virgin'],
['Antarctica/Palmer', 'GMT-4/GMT-3 Antarctica/Palmer'],
['Atlantic/Bermuda', 'GMT-4/GMT-3 Atlantic/Bermuda'],
['Atlantic/Stanley', 'GMT-4/GMT-3 Atlantic/Stanley'],
['Brazil/West', 'GMT-4 Brazil/West'],
['Canada/Atlantic', 'GMT-4/GMT-3 Canada/Atlantic'],
['Chile/Continental', 'GMT-4/GMT-3 Chile/Continental'],
['PRT', 'GMT-4 PRT'],
['America/St_Johns', 'GMT-3:30/GMT-2:30 America/St_Johns'],
['CNT', 'GMT-3:30/GMT-2:30 CNT'],
['Canada/Newfoundland', 'GMT-3:30/GMT-2:30 Canada/Newfoundland'],
['AGT', 'GMT-3/GMT-2 AGT'],
['America/Araguaina', 'GMT-3 America/Araguaina'],
['America/Argentina/Buenos_Aires', 'GMT-3/GMT-2 America/Argentina/Buenos_Aires'],
['America/Argentina/Catamarca', 'GMT-3/GMT-2 America/Argentina/Catamarca'],
['America/Argentina/ComodRivadavia', 'GMT-3/GMT-2 America/Argentina/ComodRivadavia'],
['America/Argentina/Cordoba', 'GMT-3/GMT-2 America/Argentina/Cordoba'],
['America/Argentina/Jujuy', 'GMT-3/GMT-2 America/Argentina/Jujuy'],
['America/Argentina/La_Rioja', 'GMT-3/GMT-2 America/Argentina/La_Rioja'],
['America/Argentina/Mendoza', 'GMT-3/GMT-2 America/Argentina/Mendoza'],
['America/Argentina/Rio_Gallegos', 'GMT-3/GMT-2 America/Argentina/Rio_Gallegos'],
['America/Argentina/San_Juan', 'GMT-3/GMT-2 America/Argentina/San_Juan'],
['America/Argentina/San_Luis', 'GMT-3 America/Argentina/San_Luis'],
['America/Argentina/Tucuman', 'GMT-3/GMT-2 America/Argentina/Tucuman'],
['America/Argentina/Ushuaia', 'GMT-3/GMT-2 America/Argentina/Ushuaia'],
['America/Bahia', 'GMT-3 America/Bahia'],
['America/Belem', 'GMT-3 America/Belem'],
['America/Buenos_Aires', 'GMT-3/GMT-2 America/Buenos_Aires'],
['America/Catamarca', 'GMT-3/GMT-2 America/Catamarca'],
['America/Cayenne', 'GMT-3 America/Cayenne'],
['America/Cordoba', 'GMT-3/GMT-2 America/Cordoba'],
['America/Fortaleza', 'GMT-3 America/Fortaleza'],
['America/Godthab', 'GMT-3/GMT-2 America/Godthab'],
['America/Jujuy', 'GMT-3/GMT-2 America/Jujuy'],
['America/Maceio', 'GMT-3 America/Maceio'],
['America/Mendoza', 'GMT-3/GMT-2 America/Mendoza'],
['America/Miquelon', 'GMT-3/GMT-2 America/Miquelon'],
['America/Montevideo', 'GMT-3/GMT-2 America/Montevideo'],
['America/Paramaribo', 'GMT-3 America/Paramaribo'],
['America/Recife', 'GMT-3 America/Recife'],
['America/Rosario', 'GMT-3/GMT-2 America/Rosario'],
['America/Sao_Paulo', 'GMT-3/GMT-2 America/Sao_Paulo'],
['Antarctica/Rothera', 'GMT-3 Antarctica/Rothera'],
['BET', 'GMT-3/GMT-2 BET'],
['Brazil/East', 'GMT-3/GMT-2 Brazil/East'],
['America/Noronha', 'GMT-2 America/Noronha'],
['Atlantic/South_Georgia', 'GMT-2 Atlantic/South_Georgia'],
['Brazil/DeNoronha', 'GMT-2 Brazil/DeNoronha'],
['America/Scoresbysund', 'GMT-1/GMT+0 America/Scoresbysund'],
['Atlantic/Azores', 'GMT-1/GMT+0 Atlantic/Azores'],
['Atlantic/Cape_Verde', 'GMT-1 Atlantic/Cape_Verde'],
['Africa/Abidjan', 'GMT+0 Africa/Abidjan'],
['Africa/Accra', 'GMT+0 Africa/Accra'],
['Africa/Bamako', 'GMT+0 Africa/Bamako'],
['Africa/Banjul', 'GMT+0 Africa/Banjul'],
['Africa/Bissau', 'GMT+0 Africa/Bissau'],
['Africa/Casablanca', 'GMT+0 Africa/Casablanca'],
['Africa/Conakry', 'GMT+0 Africa/Conakry'],
['Africa/Dakar', 'GMT+0 Africa/Dakar'],
['Africa/El_Aaiun', 'GMT+0 Africa/El_Aaiun'],
['Africa/Freetown', 'GMT+0 Africa/Freetown'],
['Africa/Lome', 'GMT+0 Africa/Lome'],
['Africa/Monrovia', 'GMT+0 Africa/Monrovia'],
['Africa/Nouakchott', 'GMT+0 Africa/Nouakchott'],
['Africa/Ouagadougou', 'GMT+0 Africa/Ouagadougou'],
['Africa/Sao_Tome', 'GMT+0 Africa/Sao_Tome'],
['Africa/Timbuktu', 'GMT+0 Africa/Timbuktu'],
['America/Danmarkshavn', 'GMT+0 America/Danmarkshavn'],
['Atlantic/Canary', 'GMT+0/GMT+1 Atlantic/Canary'],
['Atlantic/Faeroe', 'GMT+0/GMT+1 Atlantic/Faeroe'],
['Atlantic/Faroe', 'GMT+0/GMT+1 Atlantic/Faroe'],
['Atlantic/Madeira', 'GMT+0/GMT+1 Atlantic/Madeira'],
['Atlantic/Reykjavik', 'GMT+0 Atlantic/Reykjavik'],
['Atlantic/St_Helena', 'GMT+0 Atlantic/St_Helena'],
['Eire', 'GMT+0/GMT+1 Eire'],
['Europe/Belfast', 'GMT+0/GMT+1 Europe/Belfast'],
['Europe/Dublin', 'GMT+0/GMT+1 Europe/Dublin'],
['Europe/Guernsey', 'GMT+0/GMT+1 Europe/Guernsey'],
['Europe/Isle_of_Man', 'GMT+0/GMT+1 Europe/Isle_of_Man'],
['Europe/Jersey', 'GMT+0/GMT+1 Europe/Jersey'],
['Europe/Lisbon', 'GMT+0/GMT+1 Europe/Lisbon'],
['Europe/London', 'GMT+0/GMT+1 Europe/London'],
['GB', 'GMT+0/GMT+1 GB'],
['GB-Eire', 'GMT+0/GMT+1 GB-Eire'],
['GMT', 'GMT+0 GMT'],
['GMT0', 'GMT+0 GMT0'],
['Greenwich', 'GMT+0 Greenwich'],
['Iceland', 'GMT+0 Iceland'],
['Portugal', 'GMT+0/GMT+1 Portugal'],
['UCT', 'GMT+0 UCT'],
['UTC', 'GMT+0 UTC'],
['Universal', 'GMT+0 Universal'],
['WET', 'GMT+0/GMT+1 WET'],
['Zulu', 'GMT+0 Zulu'],
['Africa/Algiers', 'GMT+1 Africa/Algiers'],
['Africa/Bangui', 'GMT+1 Africa/Bangui'],
['Africa/Brazzaville', 'GMT+1 Africa/Brazzaville'],
['Africa/Ceuta', 'GMT+1/GMT+2 Africa/Ceuta'],
['Africa/Douala', 'GMT+1 Africa/Douala'],
['Africa/Kinshasa', 'GMT+1 Africa/Kinshasa'],
['Africa/Lagos', 'GMT+1 Africa/Lagos'],
['Africa/Libreville', 'GMT+1 Africa/Libreville'],
['Africa/Luanda', 'GMT+1 Africa/Luanda'],
['Africa/Malabo', 'GMT+1 Africa/Malabo'],
['Africa/Ndjamena', 'GMT+1 Africa/Ndjamena'],
['Africa/Niamey', 'GMT+1 Africa/Niamey'],
['Africa/Porto-Novo', 'GMT+1 Africa/Porto-Novo'],
['Africa/Tunis', 'GMT+1/GMT+2 Africa/Tunis'],
['Africa/Windhoek', 'GMT+1/GMT+2 Africa/Windhoek'],
['Arctic/Longyearbyen', 'GMT+1/GMT+2 Arctic/Longyearbyen'],
['Atlantic/Jan_Mayen', 'GMT+1/GMT+2 Atlantic/Jan_Mayen'],
['CET', 'GMT+1/GMT+2 CET'],
['ECT', 'GMT+1/GMT+2 ECT'],
['Europe/Amsterdam', 'GMT+1/GMT+2 Europe/Amsterdam'],
['Europe/Andorra', 'GMT+1/GMT+2 Europe/Andorra'],
['Europe/Belgrade', 'GMT+1/GMT+2 Europe/Belgrade'],
['Europe/Berlin', 'GMT+1/GMT+2 Europe/Berlin'],
['Europe/Bratislava', 'GMT+1/GMT+2 Europe/Bratislava'],
['Europe/Brussels', 'GMT+1/GMT+2 Europe/Brussels'],
['Europe/Budapest', 'GMT+1/GMT+2 Europe/Budapest'],
['Europe/Copenhagen', 'GMT+1/GMT+2 Europe/Copenhagen'],
['Europe/Gibraltar', 'GMT+1/GMT+2 Europe/Gibraltar'],
['Europe/Ljubljana', 'GMT+1/GMT+2 Europe/Ljubljana'],
['Europe/Luxembourg', 'GMT+1/GMT+2 Europe/Luxembourg'],
['Europe/Madrid', 'GMT+1/GMT+2 Europe/Madrid'],
['Europe/Malta', 'GMT+1/GMT+2 Europe/Malta'],
['Europe/Monaco', 'GMT+1/GMT+2 Europe/Monaco'],
['Europe/Oslo', 'GMT+1/GMT+2 Europe/Oslo'],
['Europe/Paris', 'GMT+1/GMT+2 Europe/Paris'],
['Europe/Podgorica', 'GMT+1/GMT+2 Europe/Podgorica'],
['Europe/Prague', 'GMT+1/GMT+2 Europe/Prague'],
['Europe/Rome', 'GMT+1/GMT+2 Europe/Rome'],
['Europe/San_Marino', 'GMT+1/GMT+2 Europe/San_Marino'],
['Europe/Sarajevo', 'GMT+1/GMT+2 Europe/Sarajevo'],
['Europe/Skopje', 'GMT+1/GMT+2 Europe/Skopje'],
['Europe/Stockholm', 'GMT+1/GMT+2 Europe/Stockholm'],
['Europe/Tirane', 'GMT+1/GMT+2 Europe/Tirane'],
['Europe/Vaduz', 'GMT+1/GMT+2 Europe/Vaduz'],
['Europe/Vatican', 'GMT+1/GMT+2 Europe/Vatican'],
['Europe/Vienna', 'GMT+1/GMT+2 Europe/Vienna'],
['Europe/Warsaw', 'GMT+1/GMT+2 Europe/Warsaw'],
['Europe/Zagreb', 'GMT+1/GMT+2 Europe/Zagreb'],
['Europe/Zurich', 'GMT+1/GMT+2 Europe/Zurich'],
['MET', 'GMT+1/GMT+2 MET'],
['Poland', 'GMT+1/GMT+2 Poland'],
['ART', 'GMT+2/GMT+3 ART'],
['Africa/Blantyre', 'GMT+2 Africa/Blantyre'],
['Africa/Bujumbura', 'GMT+2 Africa/Bujumbura'],
['Africa/Cairo', 'GMT+2/GMT+3 Africa/Cairo'],
['Africa/Gaborone', 'GMT+2 Africa/Gaborone'],
['Africa/Harare', 'GMT+2 Africa/Harare'],
['Africa/Johannesburg', 'GMT+2 Africa/Johannesburg'],
['Africa/Kigali', 'GMT+2 Africa/Kigali'],
['Africa/Lubumbashi', 'GMT+2 Africa/Lubumbashi'],
['Africa/Lusaka', 'GMT+2 Africa/Lusaka'],
['Africa/Maputo', 'GMT+2 Africa/Maputo'],
['Africa/Maseru', 'GMT+2 Africa/Maseru'],
['Africa/Mbabane', 'GMT+2 Africa/Mbabane'],
['Africa/Tripoli', 'GMT+2 Africa/Tripoli'],
['Asia/Amman', 'GMT+2/GMT+3 Asia/Amman'],
['Asia/Beirut', 'GMT+2/GMT+3 Asia/Beirut'],
['Asia/Damascus', 'GMT+2/GMT+3 Asia/Damascus'],
['Asia/Gaza', 'GMT+2/GMT+3 Asia/Gaza'],
['Asia/Istanbul', 'GMT+2/GMT+3 Asia/Istanbul'],
['Asia/Jerusalem', 'GMT+2/GMT+3 Asia/Jerusalem'],
['Asia/Nicosia', 'GMT+2/GMT+3 Asia/Nicosia'],
['Asia/Tel_Aviv', 'GMT+2/GMT+3 Asia/Tel_Aviv'],
['CAT', 'GMT+2 CAT'],
['EET', 'GMT+2/GMT+3 EET'],
['Egypt', 'GMT+2/GMT+3 Egypt'],
['Europe/Athens', 'GMT+2/GMT+3 Europe/Athens'],
['Europe/Bucharest', 'GMT+2/GMT+3 Europe/Bucharest'],
['Europe/Chisinau', 'GMT+2/GMT+3 Europe/Chisinau'],
['Europe/Helsinki', 'GMT+2/GMT+3 Europe/Helsinki'],
['Europe/Istanbul', 'GMT+2/GMT+3 Europe/Istanbul'],
['Europe/Kaliningrad', 'GMT+2/GMT+3 Europe/Kaliningrad'],
['Europe/Kiev', 'GMT+2/GMT+3 Europe/Kiev'],
['Europe/Mariehamn', 'GMT+2/GMT+3 Europe/Mariehamn'],
['Europe/Minsk', 'GMT+2/GMT+3 Europe/Minsk'],
['Europe/Nicosia', 'GMT+2/GMT+3 Europe/Nicosia'],
['Europe/Riga', 'GMT+2/GMT+3 Europe/Riga'],
['Europe/Simferopol', 'GMT+2/GMT+3 Europe/Simferopol'],
['Europe/Sofia', 'GMT+2/GMT+3 Europe/Sofia'],
['Europe/Tallinn', 'GMT+2/GMT+3 Europe/Tallinn'],
['Europe/Tiraspol', 'GMT+2/GMT+3 Europe/Tiraspol'],
['Europe/Uzhgorod', 'GMT+2/GMT+3 Europe/Uzhgorod'],
['Europe/Vilnius', 'GMT+2/GMT+3 Europe/Vilnius'],
['Europe/Zaporozhye', 'GMT+2/GMT+3 Europe/Zaporozhye'],
['Israel', 'GMT+2/GMT+3 Israel'],
['Libya', 'GMT+2 Libya'],
['Turkey', 'GMT+2/GMT+3 Turkey'],
['Africa/Addis_Ababa', 'GMT+3 Africa/Addis_Ababa'],
['Africa/Asmara', 'GMT+3 Africa/Asmara'],
['Africa/Asmera', 'GMT+3 Africa/Asmera'],
['Africa/Dar_es_Salaam', 'GMT+3 Africa/Dar_es_Salaam'],
['Africa/Djibouti', 'GMT+3 Africa/Djibouti'],
['Africa/Kampala', 'GMT+3 Africa/Kampala'],
['Africa/Khartoum', 'GMT+3 Africa/Khartoum'],
['Africa/Mogadishu', 'GMT+3 Africa/Mogadishu'],
['Africa/Nairobi', 'GMT+3 Africa/Nairobi'],
['Antarctica/Syowa', 'GMT+3 Antarctica/Syowa'],
['Asia/Aden', 'GMT+3 Asia/Aden'],
['Asia/Baghdad', 'GMT+3 Asia/Baghdad'],
['Asia/Bahrain', 'GMT+3 Asia/Bahrain'],
['Asia/Kuwait', 'GMT+3 Asia/Kuwait'],
['Asia/Qatar', 'GMT+3 Asia/Qatar'],
['Asia/Riyadh', 'GMT+3 Asia/Riyadh'],
['EAT', 'GMT+3 EAT'],
['Europe/Moscow', 'GMT+3/GMT+4 Europe/Moscow'],
['Europe/Volgograd', 'GMT+3/GMT+4 Europe/Volgograd'],
['Indian/Antananarivo', 'GMT+3 Indian/Antananarivo'],
['Indian/Comoro', 'GMT+3 Indian/Comoro'],
['Indian/Mayotte', 'GMT+3 Indian/Mayotte'],
['W-SU', 'GMT+3/GMT+4 W-SU'],
['Asia/Tehran', 'GMT+3:30/GMT+4:30 Asia/Tehran'],
['Iran', 'GMT+3:30/GMT+4:30 Iran'],
['Asia/Baku', 'GMT+4/GMT+5 Asia/Baku'],
['Asia/Dubai', 'GMT+4 Asia/Dubai'],
['Asia/Muscat', 'GMT+4 Asia/Muscat'],
['Asia/Tbilisi', 'GMT+4 Asia/Tbilisi'],
['Asia/Yerevan', 'GMT+4/GMT+5 Asia/Yerevan'],
['Europe/Samara', 'GMT+4/GMT+5 Europe/Samara'],
['Indian/Mahe', 'GMT+4 Indian/Mahe'],
['Indian/Mauritius', 'GMT+4 Indian/Mauritius'],
['Indian/Reunion', 'GMT+4 Indian/Reunion'],
['NET', 'GMT+4/GMT+5 NET'],
['Asia/Kabul', 'GMT+4:30 Asia/Kabul'],
['Asia/Aqtau', 'GMT+5 Asia/Aqtau'],
['Asia/Aqtobe', 'GMT+5 Asia/Aqtobe'],
['Asia/Ashgabat', 'GMT+5 Asia/Ashgabat'],
['Asia/Ashkhabad', 'GMT+5 Asia/Ashkhabad'],
['Asia/Dushanbe', 'GMT+5 Asia/Dushanbe'],
['Asia/Karachi', 'GMT+5 Asia/Karachi'],
['Asia/Oral', 'GMT+5 Asia/Oral'],
['Asia/Samarkand', 'GMT+5 Asia/Samarkand'],
['Asia/Tashkent', 'GMT+5 Asia/Tashkent'],
['Asia/Yekaterinburg', 'GMT+5/GMT+6 Asia/Yekaterinburg'],
['Indian/Kerguelen', 'GMT+5 Indian/Kerguelen'],
['Indian/Maldives', 'GMT+5 Indian/Maldives'],
['PLT', 'GMT+5 PLT'],
['Asia/Calcutta', 'GMT+5:30 Asia/Calcutta'],
['Asia/Colombo', 'GMT+5:30 Asia/Colombo'],
['Asia/Kolkata', 'GMT+5:30 Asia/Kolkata'],
['IST', 'GMT+5:30 IST'],
['Asia/Katmandu', 'GMT+5:45 Asia/Katmandu'],
['Antarctica/Mawson', 'GMT+6 Antarctica/Mawson'],
['Antarctica/Vostok', 'GMT+6 Antarctica/Vostok'],
['Asia/Almaty', 'GMT+6 Asia/Almaty'],
['Asia/Bishkek', 'GMT+6 Asia/Bishkek'],
['Asia/Dacca', 'GMT+6 Asia/Dacca'],
['Asia/Dhaka', 'GMT+6 Asia/Dhaka'],
['Asia/Novosibirsk', 'GMT+6/GMT+7 Asia/Novosibirsk'],
['Asia/Omsk', 'GMT+6/GMT+7 Asia/Omsk'],
['Asia/Qyzylorda', 'GMT+6 Asia/Qyzylorda'],
['Asia/Thimbu', 'GMT+6 Asia/Thimbu'],
['Asia/Thimphu', 'GMT+6 Asia/Thimphu'],
['BST', 'GMT+6 BST'],
['Indian/Chagos', 'GMT+6 Indian/Chagos'],
['Asia/Rangoon', 'GMT+6:30 Asia/Rangoon'],
['Indian/Cocos', 'GMT+6:30 Indian/Cocos'],
['Antarctica/Davis', 'GMT+7 Antarctica/Davis'],
['Asia/Bangkok', 'GMT+7 Asia/Bangkok'],
['Asia/Ho_Chi_Minh', 'GMT+7 Asia/Ho_Chi_Minh'],
['Asia/Hovd', 'GMT+7 Asia/Hovd'],
['Asia/Jakarta', 'GMT+7 Asia/Jakarta'],
['Asia/Krasnoyarsk', 'GMT+7/GMT+8 Asia/Krasnoyarsk'],
['Asia/Phnom_Penh', 'GMT+7 Asia/Phnom_Penh'],
['Asia/Pontianak', 'GMT+7 Asia/Pontianak'],
['Asia/Saigon', 'GMT+7 Asia/Saigon'],
['Asia/Vientiane', 'GMT+7 Asia/Vientiane'],
['Indian/Christmas', 'GMT+7 Indian/Christmas'],
['VST', 'GMT+7 VST'],
['Antarctica/Casey', 'GMT+8 Antarctica/Casey'],
['Asia/Brunei', 'GMT+8 Asia/Brunei'],
['Asia/Chongqing', 'GMT+8 Asia/Chongqing'],
['Asia/Chungking', 'GMT+8 Asia/Chungking'],
['Asia/Harbin', 'GMT+8 Asia/Harbin'],
['Asia/Hong_Kong', 'GMT+8 Asia/Hong_Kong'],
['Asia/Irkutsk', 'GMT+8/GMT+9 Asia/Irkutsk'],
['Asia/Kashgar', 'GMT+8 Asia/Kashgar'],
['Asia/Kuala_Lumpur', 'GMT+8 Asia/Kuala_Lumpur'],
['Asia/Kuching', 'GMT+8 Asia/Kuching'],
['Asia/Macao', 'GMT+8 Asia/Macao'],
['Asia/Macau', 'GMT+8 Asia/Macau'],
['Asia/Makassar', 'GMT+8 Asia/Makassar'],
['Asia/Manila', 'GMT+8 Asia/Manila'],
['Asia/Shanghai', 'GMT+8 Asia/Shanghai'],
['Asia/Singapore', 'GMT+8 Asia/Singapore'],
['Asia/Taipei', 'GMT+8 Asia/Taipei'],
['Asia/Ujung_Pandang', 'GMT+8 Asia/Ujung_Pandang'],
['Asia/Ulaanbaatar', 'GMT+8 Asia/Ulaanbaatar'],
['Asia/Ulan_Bator', 'GMT+8 Asia/Ulan_Bator'],
['Asia/Urumqi', 'GMT+8 Asia/Urumqi'],
['Australia/Perth', 'GMT+8 Australia/Perth'],
['Australia/West', 'GMT+8 Australia/West'],
['CTT', 'GMT+8 CTT'],
['Hongkong', 'GMT+8 Hongkong'],
['PRC', 'GMT+8 PRC'],
['Singapore', 'GMT+8 Singapore'],
['Australia/Eucla', 'GMT+8:45 Australia/Eucla'],
['Asia/Choibalsan', 'GMT+9 Asia/Choibalsan'],
['Asia/Dili', 'GMT+9 Asia/Dili'],
['Asia/Jayapura', 'GMT+9 Asia/Jayapura'],
['Asia/Pyongyang', 'GMT+9 Asia/Pyongyang'],
['Asia/Seoul', 'GMT+9 Asia/Seoul'],
['Asia/Tokyo', 'GMT+9 Asia/Tokyo'],
['Asia/Yakutsk', 'GMT+9/GMT+10 Asia/Yakutsk'],
['JST', 'GMT+9 JST'],
['Japan', 'GMT+9 Japan'],
['Pacific/Palau', 'GMT+9 Pacific/Palau'],
['ROK', 'GMT+9 ROK'],
['ACT', 'GMT+9:30 ACT'],
['Australia/Adelaide', 'GMT+9:30/GMT+10:30 Australia/Adelaide'],
['Australia/Broken_Hill', 'GMT+9:30/GMT+10:30 Australia/Broken_Hill'],
['Australia/Darwin', 'GMT+9:30 Australia/Darwin'],
['Australia/North', 'GMT+9:30 Australia/North'],
['Australia/South', 'GMT+9:30/GMT+10:30 Australia/South'],
['Australia/Yancowinna', 'GMT+9:30/GMT+10:30 Australia/Yancowinna'],
['AET', 'GMT+10/GMT+11 AET'],
['Antarctica/DumontDUrville', 'GMT+10 Antarctica/DumontDUrville'],
['Asia/Sakhalin', 'GMT+10/GMT+11 Asia/Sakhalin'],
['Asia/Vladivostok', 'GMT+10/GMT+11 Asia/Vladivostok'],
['Australia/ACT', 'GMT+10/GMT+11 Australia/ACT'],
['Australia/Brisbane', 'GMT+10 Australia/Brisbane'],
['Australia/Canberra', 'GMT+10/GMT+11 Australia/Canberra'],
['Australia/Currie', 'GMT+10/GMT+11 Australia/Currie'],
['Australia/Hobart', 'GMT+10/GMT+11 Australia/Hobart'],
['Australia/Lindeman', 'GMT+10 Australia/Lindeman'],
['Australia/Melbourne', 'GMT+10/GMT+11 Australia/Melbourne'],
['Australia/NSW', 'GMT+10/GMT+11 Australia/NSW'],
['Australia/Queensland', 'GMT+10 Australia/Queensland'],
['Australia/Sydney', 'GMT+10/GMT+11 Australia/Sydney'],
['Australia/Tasmania', 'GMT+10/GMT+11 Australia/Tasmania'],
['Australia/Victoria', 'GMT+10/GMT+11 Australia/Victoria'],
['Pacific/Guam', 'GMT+10 Pacific/Guam'],
['Pacific/Port_Moresby', 'GMT+10 Pacific/Port_Moresby'],
['Pacific/Saipan', 'GMT+10 Pacific/Saipan'],
['Pacific/Truk', 'GMT+10 Pacific/Truk'],
['Pacific/Yap', 'GMT+10 Pacific/Yap'],
['Australia/LHI', 'GMT+10:30/GMT+11 Australia/LHI'],
['Australia/Lord_Howe', 'GMT+10:30/GMT+11 Australia/Lord_Howe'],
['Asia/Magadan', 'GMT+11/GMT+12 Asia/Magadan'],
['Pacific/Efate', 'GMT+11 Pacific/Efate'],
['Pacific/Guadalcanal', 'GMT+11 Pacific/Guadalcanal'],
['Pacific/Kosrae', 'GMT+11 Pacific/Kosrae'],
['Pacific/Noumea', 'GMT+11 Pacific/Noumea'],
['Pacific/Ponape', 'GMT+11 Pacific/Ponape'],
['SST', 'GMT+11 SST'],
['Pacific/Norfolk', 'GMT+11:30 Pacific/Norfolk'],
['Antarctica/McMurdo', 'GMT+12/GMT+13 Antarctica/McMurdo'],
['Antarctica/South_Pole', 'GMT+12/GMT+13 Antarctica/South_Pole'],
['Asia/Anadyr', 'GMT+12/GMT+13 Asia/Anadyr'],
['Asia/Kamchatka', 'GMT+12/GMT+13 Asia/Kamchatka'],
['Kwajalein', 'GMT+12 Kwajalein'],
['NST', 'GMT+12/GMT+13 NST'],
['NZ', 'GMT+12/GMT+13 NZ'],
['Pacific/Auckland', 'GMT+12/GMT+13 Pacific/Auckland'],
['Pacific/Fiji', 'GMT+12 Pacific/Fiji'],
['Pacific/Funafuti', 'GMT+12 Pacific/Funafuti'],
['Pacific/Kwajalein', 'GMT+12 Pacific/Kwajalein'],
['Pacific/Majuro', 'GMT+12 Pacific/Majuro'],
['Pacific/Nauru', 'GMT+12 Pacific/Nauru'],
['Pacific/Tarawa', 'GMT+12 Pacific/Tarawa'],
['Pacific/Wake', 'GMT+12 Pacific/Wake'],
['Pacific/Wallis', 'GMT+12 Pacific/Wallis'],
['NZ-CHAT', 'GMT+12:45/GMT+13:45 NZ-CHAT'],
['Pacific/Chatham', 'GMT+12:45/GMT+13:45 Pacific/Chatham'],
['Pacific/Enderbury', 'GMT+13 Pacific/Enderbury'],
['Pacific/Tongatapu', 'GMT+13 Pacific/Tongatapu'],
['Pacific/Kiritimati', 'GMT+14 Pacific/Kiritimati']
];

var editProfile = function(noteid, selectNote){
	
	var name = new Ext.form.TextField({
		fieldLabel: 'Name',
		allowBlank: false,
		value: user.name,
		msgTarget: 'under'
	});
	
	var email = new Ext.form.TextField({
		fieldLabel: 'E-mail',
		value: user.email
	}); 
	
	var dateFormatField = new Ext.form.ComboBox({
		fieldLabel: 'Date format',
		store: new Ext.data.SimpleStore({
			fields: ['id', 'name'],
			data: [
				["dd/MM/yy", "dd/mm/yy (14/10/08)"],
				["MM/dd/yy", "mm/dd/yy (10/14/08)"],
				["dd.MM.yy", "dd.mm.yy (14.10.08)"],
				["yy-MM-dd", "yy-mm-dd (08-10-14)"]
			]
		}),
		displayField: 'name',
		valueField: 'id',
		forceSelection: true,
		triggerAction: 'all',
		selectOnFocus:true,
		editable: false,
		mode: 'local',
		value: user.dateFormat
	});
	
	var timeFormatField = new Ext.form.ComboBox({
		fieldLabel: 'Time format',
		store: new Ext.data.SimpleStore({
			fields: ['id', 'name'],
			data: [
				["h:mm a", "12-hour (2:15 PM)"],
				["H:mm", "24-hour (14:15)"]
			]
		}),
		displayField: 'name',
		valueField: 'id',
		forceSelection: true,
		triggerAction: 'all',
		selectOnFocus:true,
		editable: false,
		mode: 'local',
		value: user.timeFormat
	});
	
	var minuteOffset = new Ext.form.ComboBox({
		fieldLabel: 'Time zone',
		store: new Ext.data.SimpleStore({
			fields: ['id', 'name'],
			data: tz
		}),
		displayField: 'name',
		valueField: 'id',
		forceSelection: true,
		triggerAction: 'all',
		selectOnFocus:true,
		editable: false,
		mode: 'local',
		value: user.timeZone
	});
	
	var oldPass = new Ext.form.TextField({
		fieldLabel: 'Old password',
		msgTarget: 'under',
		inputType: 'password'
	});
	
	var newPass = new Ext.form.TextField({
		fieldLabel: 'New password',
		msgTarget: 'under',
		inputType: 'password'
	});
	
	var newPass2 = new Ext.form.TextField({
		fieldLabel: 'Retype password',
		msgTarget: 'under',
		inputType: 'password'
	});
	
	var form = new Ext.form.FormPanel({
		frame: true,
		defaults: {anchor: '100%'},
		defaultType: 'textfield',
		labelAlign: 'right',
		autoHeight: true,
		items:[
			{
				title: 'Personal information',
				defaults: {anchor: '100%'},
				autoHeight:true,
				xtype: 'fieldset',
				items: [
					name, email, dateFormatField, timeFormatField, minuteOffset
				]
			},{
				title: 'If you want to change password, fill this form',
				defaults: {anchor: '100%'},
				autoHeight:true,
				xtype: 'fieldset',
				items: [
					oldPass, newPass, newPass2
				]
			}
			
		],
		buttons:[
			{
				text: 'Save',
				handler: function(){
					if(form.getForm().isValid()){
						if(oldPass.getValue()){
							if(!newPass.getValue()){
								newPass.markInvalid('Now this field is required');
								return;
							}
							if(newPass.getValue()!=newPass2.getValue()){
								newPass2.markInvalid('Passwords don\'t match');
								return;
							}
						}
						callAPI('user.UpdateUser', {
							object:{
								user:{
									name: name.getValue(),
									email: email.getValue(),
									dateFormat: dateFormatField.getValue(),
									timeFormat: timeFormatField.getValue(),
									timeZone: minuteOffset.getValue(),
									language: user.language
								}
							}
						}, function(object){
							user = object.user;
							recalcFormats();
							if(oldPass.getValue()){
								callAPI('user.UpdatePassword', {
									oldpassword: hex_md5(oldPass.getValue()),
									newpassword: hex_md5(newPass.getValue())
								}, function(object){
									oldPass.setValue('');
									newPass.setValue('');
									newPass2.setValue('');
									token = object.user.token;
									showInfo('Profile updated. Password updated');
								})
							}else{
								showInfo('Profile updated');
							}
							recalcFormats();
						})
					}
				}
			}
		]
	});
	var win = new Ext.Window({
		width: 500,
		plain: true,
		autoHeight: true,
		title: 'Your profile ('+user.login+'):',
		modal: true,
		layout: 'fit',
		onEsc: Ext.emptyFn,
		items: form
	});
	win.on('close', function(){
		selectNote(noteid);
	});
	setTitle('Your profile ('+user.login+')')
	win.show();
}